我正在使用pre_get_posts
然而,由于hook没有按预期工作,我发现函数被调用了4次,当第一个调用按预期运行时,后续调用将无法正确运行。我想知道为什么我的自定义挂钩被运行了不止一次!
我找到了一个article that explains why this may happen, 但我很困惑,因为就我而言,这根本不应该发生。。。。
代码:
function exclude_category( $query ) {
global $acorn_user;
$tax_query = array();
if ( $query->is_feed ) {
/**** Exclude "exclude" category posts from feed ********/
$query->set(\'cat\', \'-617, -618\');
return $query;
}
$args = array(
\'category__not_in\' => 2 ,
\'category__in\' => 22,
\'posts_per_page\' => 7,
\'post_status\' => \'publish\');
if (!is_user_logged_in() /*&& !is_admin()*/) {
/**** Exclude child categories ********/
if ($query->is_category(3) || $query->is_category(68) || $query->is_category(69) || $query->is_category(70)) {
$queried_object = get_queried_object();
$child_cats = (array)get_term_children($queried_object->term_id, \'category\');
if (!$query->is_admin) {
//exclude the posts in child categories
$tax_query[] = array(\'category__not_in\', array(68, 69, 70, 81, 82, 83));
}
}
}
//exclude search results for parents & teachers & non logged users
if ( $query->is_search && $query->is_main_query() ) {
if(empty($acorn_user) || !in_array( \'teacher\', (array) $acorn_user->roles )) {
$tax_query[] = array(\'post__not_in\', array(30140, 30020, 30008, 29998, 29991, 21458,20197,11986,6614));
}
}
if (!empty($tax_query)) {
$query->set(\'tax_query\', $tax_query);
}
return $query;
}
add_filter( \'pre_get_posts\', \'exclude_category\' );