首页 > 解决方案 > WordPress如何根据特定类别查询页面

问题描述

我将类别添加到页面,并创建了一个用于特定页面的模板。此页面必须仅显示 2 个类别的帖子:

这是我的代码:

    <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 页面帖子,如果单击“category2”,则仅显示 category2 页面帖子。谢谢。

标签: wordpresswordpress-themingcategoriescustom-wordpress-pages

解决方案


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

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

  • 'post_type'
  • 'post_status'
  • 'child_of'
  • '排序'
  • '排序列'
  • '分层'
  • '排除'
  • '包括'
  • '元密钥'
  • “元值”
  • “作者”
  • '父母'
  • '排除树'
  • '数字'
  • '抵消'

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

  • 假设您使用的是通用 wordpress,category而不是由 ACF 和此类插件构建的自定义类别!
  • 此外,假设您想使用slug您的类别。
$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并且可以无缝运行!如果您有任何其他问题,请告诉我。


推荐阅读