php WordPress:如何使用 $wp_query 按类别过滤帖子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41886528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WordPress: How to filter posts by category using $wp_query?
提问by acidgate
I built a custom theme on WordPress with a static front page and no page set in Settings > Reading Settings > Front page displaysas a posts page. I'd like to display posts, however, based on their categories throughout the site on different static pages. Therefore, I will never declare a posts index page through the console. And so I use the $wp_query function.
我在 WordPress 上构建了一个带有静态首页的自定义主题,并且在“设置”>“阅读设置”>“首页”中没有设置页面显示为帖子页面。但是,我想根据帖子的类别在整个网站的不同静态页面上显示帖子。因此,我永远不会通过控制台声明帖子索引页面。所以我使用 $wp_query 函数。
How can I add a filter to this script that only displays posts in the category "apples" (for example)? Right now, this script shows all posts regardless of category.
如何向此脚本添加过滤器,仅显示“苹果”类别中的帖子(例如)?现在,此脚本显示所有帖子,而不考虑类别。
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php the_date(); ?>
<?php endwhile; ?>
<?php if ($paged > 1) { ?>
<p><?php previous_posts_link('Previous page'); ?>
<?php next_posts_link('Next page'); ?></p>
<?php } else { ?>
<p><?php next_posts_link('Next page'); ?></p>
<?php } ?>
<?php wp_reset_postdata(); ?>
回答by Raunak Gupta
You have to use
category_name
(string - use category slug) orcat
(int - use category id), to get post by category inWP_Query::query()
.
您必须使用
category_name
(string - use category slug) 或cat
(int - use category id),才能在WP_Query::query()
.
Here is an example:
下面是一个例子:
$category_name = 'apples'; //replace it with your category slug
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=1' . '&paged=' . $paged . '&category_name=' . $category_name);
//...
//...
Hope this helps!
希望这可以帮助!
回答by Ed Dogan
Delete your first php block and replace it with this
删除您的第一个 php 块并将其替换为
<?php
$args = array (
'showposts' => '1',
'category_name' => 'apples',
'paged' => $paged
);
$the_query = new WP_Query( $args );
if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
?>
For more information https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
有关更多信息https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters