wordpress - WordPress如何根据特定类别查询页面
问题描述
我将类别添加到页面,并创建了一个用于特定页面的模板。此页面必须仅显示 2 个类别的帖子:
- (第 1 类,第 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 页面帖子。谢谢。
解决方案
但它不起作用,它显示所有页面
是的get_pages
函数接受几个参数,但是,'category_name'
不是其中之一!get_pages
以下是可识别的参数列表: get_pages
Docs
- 'post_type'
- 'post_status'
- 'child_of'
- '排序'
- '排序列'
- '分层'
- '排除'
- '包括'
- '元密钥'
- “元值”
- “作者”
- '父母'
- '排除树'
- '数字'
- '抵消'
现在,如果您想根据特定类别查询您的页面,那么您可以使用wp_query
Docs。
- 假设您使用的是通用 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
并且可以无缝运行!如果您有任何其他问题,请告诉我。
推荐阅读
- xml - 使用 XQL 进行字符串连接
- python - TensorFlow 图像处理函数
- javascript - 我的 php 脚本不能很好地执行(XmlHttpReqest)
- c# - 如何使用 devexpress 编辑网格控件中的数据并将其保存到数据库
- angular - 返回 http 400 状态码不起作用
- c# - 在 Main() 之前调用的隐式静态构造函数
- google-chrome - 当我尝试在 chrome 和 safari 中登录 iframe 时出现错误,但在 mozilla firefox 中正常工作
- emscripten - 我如何告诉 Emscripten 记录它使用 Asyncify 处理的功能?
- android - 在 android studio 中查看模型状态:Kotlin
- javascript - 如何在 node.js 中包含默认模型作为参考名称?