当前位置: 首页 » 教程 » WordPress查询同时在2个或者多个分类上的文章WP_Query及计算文章数量和分页处理正文

WordPress查询同时在2个或者多个分类上的文章WP_Query及计算文章数量和分页处理

  • 零分
  • 1,143

WordPress查询同时在2个或者多个分类上的文章WP_Query及计算文章数量。WP_Query和query_posts()用法参数差不多。在查询同时满足的时候,用到参数category__and

首先看下WP_Query用法

标准循环

<?php

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

标准循环(备用)

<?php 
// the query
$the_query = new WP_Query( $args ); ?>
 
<?php if ( $the_query->have_posts() ) : ?>
 
    <!-- pagination here -->
 
    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; ?>
    <!-- end of the loop -->
 
    <!-- pagination here -->
 
    <?php wp_reset_postdata(); ?>
 
<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

多个循环

<?php
 
// The Query
$query1 = new WP_Query( $args );
 
// The Loop
while ( $query1->have_posts() ) {
    $query1->the_post();
    echo '<li>' . get_the_title() . '</li>';
}
 
/* Restore original Post Data 
 * NB: Because we are using new WP_Query we aren't stomping on the 
 * original $wp_query and it does not need to be reset with 
 * wp_reset_query(). We just need to set the post data back up with
 * wp_reset_postdata().
 */
wp_reset_postdata();

/* The 2nd Query (without global var) */
$query2 = new WP_Query( $args2 );
 
// The 2nd Loop
while ( $query2->have_posts() ) {
    $query2->the_post();
    echo '<li>' . get_the_title( $query2->post->ID ) . '</li>';
}
 
// Restore original Post Data
wp_reset_postdata();
 
?>

WP_Query的更多用法可以参考官网手册说明:WP_Query函数,这里不再累述,主要写一下如何获取同时在2个或者2个以上分类的文章及计算这些文章数量还有分页

查询同时满足2个或者2个以上文章

$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );

返回文章在分类2也在分类6,也就是同时在分类2和6的文章(不显示子类目文章),返回的文章数量受到分页显示数量限制,如果需要重新设置页码数量,添加参数posts_per_page

$query = new WP_Query( array( 'category__and' => array( 2, 6 ),'posts_per_page'=>20 ) );

返回文章每页20个,但如果后台设置每页显示10篇文章,会出现一个文章,全部文章显示完之后,分页导航还在,也就是后面点击的分页内容是空白文章的分页。而且因为category__and参数,分页也会出现不正确,这时候需要修改下定义的函数,如分页导航计算数量的是$wp_query,这里也的也改成$wp_query

$wp_query = new WP_Query( array( 'category__and' => array( 2, 6 ),'posts_per_page'=>20 ) );

这样分页就改回来了,在其他页面时,用$wp_query显示,在这个需要查询多分类同时存在文章时,重新定义了$wp_query,分页也按重新定义的$wp_query分页。

$wp_query->found_posts就是返回的文章总数量了!

声明:博客中如无特殊说明或标注的文章均为博客原创文章,部分文章来源互联网,如有侵犯您的版权,或者对零分博客发布的文章有异议,请来信告知删除、修改,如您有好的建议或者意见也可以来信,谢谢!

请TA喝杯水^_^ 如本文“对您有用”,欢迎随意打赏,让我们坚持创作! 请TA喝水