admin管理员组文章数量:1122832
I added the following to my functions.php:
add_action('pre_get_posts', 'keyl_get_emp_posts');
function keyl_get_emp_posts($query) {
if ($query->is_main_query())
$query->set('post_type', 'employee');
}
and so far it's effectively filtering out the search results. The default widgets Recent Posts and Recent Comments aren't budging, though. What gives?
I added the following to my functions.php:
add_action('pre_get_posts', 'keyl_get_emp_posts');
function keyl_get_emp_posts($query) {
if ($query->is_main_query())
$query->set('post_type', 'employee');
}
and so far it's effectively filtering out the search results. The default widgets Recent Posts and Recent Comments aren't budging, though. What gives?
Share Improve this question asked Jun 12, 2012 at 5:29 Ana BanAna Ban 8071 gold badge11 silver badges19 bronze badges2 Answers
Reset to default 0pre_get_posts is executed before each and every query. Your $query->is_main_query() is making this code change the query only for the Main query. So, if you're in an archive page, you're modifying only the archive posts, and not any of the others queries (widgets, menus, etc).
But be aware, that code you added there will change the query for ALL your main queries. So if you go to another post type archives (categories, etc) you will be modifying the query to get the post_type = employee
Both the "Recents Posts" widget and the "Recent Comments" widget provide a filter that you can use to alter the query, and they both conveniently take the same argument.
function alter_recent_widget_post_type_wpse_54931($args) {
$args['post_type'] = 'employee';
return $args;
}
add_filter('widget_posts_args','alter_recent_widget_post_type_wpse_54931');
add_filter('widget_posts_args','alter_recent_widget_post_type_wpse_54931');
That will alter the widgets every time they run so if you need the widgets to function in multiple contexts you will need something more complicated.
本文标签: wp queryHow to target the default Recent Posts and Recent Comments widgets with pregetposts
版权声明:本文标题:wp query - How to target the default Recent Posts and Recent Comments widgets with pre_get_posts? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736292870a1929027.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论