我正在尝试列出默认wordpress博客页面上仅属于某个类别的帖子。我需要通过插件添加过滤器/动作挂钩来完成此操作。我无法编辑主题模板文件。
我使用以下代码为最近的帖子列表做了这个:
add_filter('widget_posts_args', 'my_widget_posts_args');
function my_widget_posts_args($args) {
return array( 'posts_per_page' => 10,//set the number you want here
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'cat' => 52 //$cat -> term_id//the current category id
);
}
如何为帖子列表页面执行相同操作?
答案 0 :(得分:1)
我假设默认情况下wp博客页面是指首页。如果没有,请使用is_home
代替is_front_page
。
要在运行查询之前按类别过滤帖子,您需要在pre_get_posts操作挂钩中更改查询cat
的类别参数。
将以下内容添加到您的插件代码中:
add_action('pre_get_posts', 'my_post_filter');
function my_post_filter($query) {
if($query->is_front_page() && $query->is_main_query()) {
$query->set('cat', '52');
}
}
以上内容也可以在主题的functions.php中使用。