Wordpress loop to filter out by meta

2019-08-09 07:05发布

This kind of follows on from a previous question where JanW : http://bit.ly/VQy9hb

I'm trying to hide posts that contain certain meta data, in this case meta_name = "smartPrivate".

The function below works but unfortunately also affects the menu loop (it just disappears).

Does anyone know how I can hide these posts from appearing in all loops but not affect the menu (and who knows what else...)

Thanks in advance Rob

function hide_some_posts( $query ) {

    if (!is_user_logged_in()) {

        $query->set( 'meta_query', array(

            array(
                  'key' => 'smartPrivate',
                  'value' => 'smartPrivate_loggedIn',
                  'compare' => '!='
            ),
            array(
                  'key' => 'smartPrivate',
                  'value' => 'smartPrivate_loggedInMentors',
                  'compare' => '!='
            )

        ));
    }

  return $query;
}
add_filter( 'pre_get_posts', 'hide_some_posts' );

1条回答
成全新的幸福
2楼-- · 2019-08-09 08:03

So your problem is that it affects other queries than the main query, if I understand your situation correctly. This is pretty much why is_main_query exists. So try this:

function hide_some_posts( $query ) {


    if (!is_user_logged_in() && $query->is_main_query() ) {

        $query->set( 'meta_query', array(

            array(
                  'key' => 'smartPrivate',
                  'value' => 'smartPrivate_loggedIn',
                  'compare' => '!='
            ),
            array(
                  'key' => 'smartPrivate',
                  'value' => 'smartPrivate_loggedInMentors',
                  'compare' => '!='
            )

        ));
    }

  return $query;
}
add_filter( 'pre_get_posts', 'hide_some_posts' );
查看更多
登录 后发表回答