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

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

零分教程8412022-08-13 03:43

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就是返回的文章总数量了!

END
零分站龄17年资深站长
一个喜欢折腾,却又折腾不出像样东西的,不会PHP的PHP程序员!
2517
文章
13
分类
3818
标签
3
友链
onlinelovesky317355746vipsever@vip.qq.com