Php 如何从自定义分类中访问帖子数组,以便对其进行排序?
我有一个名为mwp_ss_supp的自定义分类法。我有一个页面,其中显示了使用以下代码的所有帖子:Php 如何从自定义分类中访问帖子数组,以便对其进行排序?,php,wordpress,Php,Wordpress,我有一个名为mwp_ss_supp的自定义分类法。我有一个页面,其中显示了使用以下代码的所有帖子: <?php $count = wp_count_posts('mwp_ss_supp')->publish; echo '<div id="post-count">' . $count . ' posts displayed</div>';?> <?php if ( have_posts()
<?php $count = wp_count_posts('mwp_ss_supp')->publish;
echo '<div id="post-count">' . $count . ' posts displayed</div>';?>
<?php
if ( have_posts() ) :
while (have_posts()) : the_post();
DO STUFF
<?php
endwhile;
endif; ?>
问题是,所有帖子都是按照最新帖子在发布列表中的第一个的顺序显示的。但我想以不同的顺序打印它们(即,先发布1-10篇文章,然后发布15-20篇文章,最后发布11-14篇文章,最后按标题的字母顺序发布)。那么我如何访问这些帖子呢?似乎没有数组变量可供使用。为此显示sql查询。sql查询从数据库获取数据并确定排序,您需要构建自定义wordpress查询
WP\u query()
来根据分类查询帖子:
<?php
$args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy_type',
);
);
'orderby'=> 'title',
'order' => 'ASC',
);
/**
* WP_Query()
* The WordPress Query class.
* @link https://developer.wordpress.org/reference/classes/wp_query/
*/
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
if( get_the_title() !== '' ):
the_title( '<h1>', '</h1>' );
endif;
if( get_the_content() !== '' ):
the_content();
endif;
endwhile;
endif;
/**
* wp_reset_postdata()
* After looping through a separate query, this function restores the $post global to the current post in the main query.
* @link https://developer.wordpress.org/reference/functions/wp_reset_postdata/
*/
wp_reset_postdata(); ?>
了解更多
@wp\u查询
function taxo_posts($query)
{
if ($query->is_tax('mwp_ss_supp') && $query->is_main_query())
{
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' ); // or DESC
}
}
add_action('pre_get_posts', 'taxo_posts');
您可以在“DO STUFF”部分的数组中收集帖子。然后按照您想要的方式对它们进行排序(例如“升序”)。然后最终显示您想要的方式(例如,大列表、分页等)。这是一个实际对我最有效的方式。我浏览了
if(have_posts()):while(have_posts()):the_post()
循环并将当前的$post
放入一个数组中,然后处理它。