一种简单的方法是使用静态变量存储作者姓名,然后在以后的挂钩上再次运行相同的函数,可能是“posts\\u results”,然后设置回变量:
function wpquery( $query, $query_on_results = NULL ) {
static $author_name = NULL;
if ( current_filter() === \'pre_get_posts\' ) {
if ( $query->is_author() && $query->is_main_query() ) {
$query->set( \'post_status\', $post_status );
$author_name = $query->query_vars[\'author_name\'];
unset( $query->query_vars[\'author_name\'] );
$tax_query = array(
array(
\'taxonomy\' => \'tax\',
\'field\' => \'name\',
\'terms\' => $var
)
);
$query->set( \'tax_query\', $tax_query );
}
} elseif ( current_filter() === \'posts_results\' ) {
if ( $query_on_results->is_main_query() && ! empty( $author_name ) ) {
$query_on_results->query_vars[\'author_name\'] = $author_name;
$author_name = NULL;
remove_filter( current_filter(), __FUNCTION__, 20, 2 );
}
// $query represent the 1st arg passed to function, that on posts_result hook
// is the retrieved posts array. Always return it as is to do not alter results
return $query;
}
}
add_action( \'pre_get_posts\', \'wpquery\' );
add_filter( \'posts_results\', \'wpquery\', 20, 2 );