添加保护子句以防止修改其他查询很重要。(例如,菜单)。我们正在尝试修改这里的主查询,因此如果这不是主查询,我们应该退出。
function my_get_posts( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Other guard clauses to ensure we don\'t affect queries unintentionally.
// Sounds like you are just trying to target the homepage, so we could check for that too.
if ( ! is_home() ) {
return;
}
// We only need to modify the query for logged in users.
if ( ! is_user_logged_in() ) {
return;
}
// Modify the query as needed...
}
add_action( \'pre_get_posts\', \'my_get_posts\' ); // Note that pre_get_posts is an action, not a filter.