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



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

  • (category1 category2)。

这是我的代码:

<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>

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

最后,我必须对这两个类别使用过滤器,如果我点击"category1"它只显示类别1页面的帖子,如果我点击"只有类别2页面发布。谢谢。

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

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

  • "post_type">
  • "postrongtatus">
  • "孩子">
  • "sort_order">
  • "sort_column">
  • "分层">
  • "排除">
  • "包括">
  • "meta_key">
  • "meta_value">
  • "作者">
  • "父">
  • "exclude_tree">
  • "数量">
  • "抵消">

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

  • 假设你使用的是通用的wordpresscategory,而不是由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();

这个答案已经在wordpress5.8上进行了全面测试,并且可以无缝地工作!如果您还有什么问题,请告诉我。

最新更新