WordPress如何根据特定类别查询页面

WordPress how to query pages based on specific categories

我将类别添加到页面,并创建了一个用于特定页面的模板。 此页面只能显示 2 个类别的 post:

这是我的代码:

    <div class="container">

<div class="row">
<?php
  $pages = get_pages( array('category_name' => 'category1, category2' ) );
foreach ( $pages as $page ) {
?>
    <div class="col"> <a href="<?php echo get_page_link( $page->ID ) ?>" class="header-link"><?php echo $page->post_title ?></a>  <?php echo get_the_post_thumbnail($page->ID, 'thumbnail'); ?>  </div>


    </div></div>

但它不起作用,它显示了所有页面。

最后我必须对这 2 个类别使用过滤器,如果我单击“category1”它只显示 category1 页面 post,如果我单击“category2”只显示 category2 页面post.谢谢

but it doesn't work, it shows all pages

是的 get_pages 函数接受多个参数,但是 'category_name' 不是其中之一!以下是 get_pages 可识别的参数列表:get_pagesDocs

  • 'post_type'
  • 'post_status'
  • 'child_of'
  • 'sort_order'
  • 'sort_column'
  • 'hierarchical'
  • 'exclude'
  • 'include'
  • 'meta_key'
  • 'meta_value'
  • 'authors'
  • 'parent'
  • 'exclude_tree'
  • 'number'
  • 'offset'

现在,如果您想根据特定类别查询您的网页,那么您可以使用 wp_queryDocs

  • Assuming that you're using the generic wordpress category not a custom category built by ACF and plugins of that sort!
  • Also, assuming you want to work with the slug of your categories.
$args = array(
  'post_type' => 'page',
  'posts_per_page' => -1,
  'post_status' => array('publish', 'private'),
  'tax_query' => array(
    array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => array('test-category-01', 'test-category-02') // These are the slugs of the categories you're interested in
    )
  )
);

$all_pages = new WP_Query($args);

if ($all_pages) {
  while ($all_pages->have_posts()) {
    $all_pages->the_post(); ?>
    <div class="col">
      <a href="<?php echo get_page_link(get_the_ID()) ?>" class="header-link"><?php the_title() ?></a>
    </div>
<?php
  }
}

wp_reset_postdata();


执行上述查询的替代方法。

如果您想使用 id 个类别。

$args = array(
  'post_type' => 'page',
  'posts_per_page' => -1,
  'post_status' => array('publish', 'private'),
  'tax_query' => array(
    array(
      'taxonomy' => 'category',
      'field'    => 'term_id',
      'terms'    => array(4, 5), // These are the ids of the categories you're interested in
      'operator' => 'IN',
    ),
  )
);

$all_pages = new WP_Query($args);

if ($all_pages) {
  while ($all_pages->have_posts()) {
    $all_pages->the_post(); ?>
    <div class="col">
      <a href="<?php echo get_page_link(get_the_ID()) ?>" class="header-link"><?php the_title() ?></a>
    </div>
<?php
  }
}

wp_reset_postdata();

此答案已在 wordpress 5.8 上进行了全面测试,并且可以无缝运行!如果您有任何其他问题,请告诉我。