【问题标题】:Display sticky posts first with WP_Query and category__and首先使用 WP_Query 和 category__and 显示粘性帖子
【发布时间】:2026-02-03 19:40:01
【问题描述】:

尝试使用 WP_Query 和 category__and 显示来自多个帖子类别的常见帖子。以下是查询:

$query = array(
    'category__and' => array( 'cat-1', 'cat-2'),
    'posts_per_page' => 10,
    'paged' => $paged
    );

$cat_query = new WP_Query($query);

现在在上述情况下,帖子已正确获取,但粘性帖子不会首先显示。

以下代码解决了问题,但它不执行类别帖子的“与”。

$query = array(
    'cat' => array( 'cat-1', 'cat-2'),
    'posts_per_page' => 10,
    'paged' => $paged
    );

上述查询首先显示置顶帖子,但不对类别帖子执行“与”。

有没有什么办法可以满足置顶帖优先和多分类常见帖的条件?

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    您可以使用这些参数来显示置顶帖-

    $query_sticky = array(
      'category__and' => array( 'cat-1', 'cat-2'),
      'posts_per_page' => 10,
      'post__in' => get_option( 'sticky_posts' ),
      'ignore_sticky_posts' => 1,
      'paged' => $paged
    );
    $query_sticky = new WP_Query($query_sticky);
    

    一旦你有了这些粘性帖子,你就可以将它们合并到主查询中-

    $query->posts = array_merge($query->posts, $query_sticky->posts);
    $query->post = reset($query->posts);
    $query->post_count += $query_sticky->post_count;
    $query->found_posts += $query_sticky->found_posts;
    $query->max_num_pages = $query->found_posts / $query->get('posts_per_page');
    

    post_count 等变量是使 wordpress 循环正常工作所必需的。

    【讨论】:

    • 如果查询是分页的,这会在每个页面上的类别帖子顶部附加粘性帖子。