query - How to exclude posts for current user

admin2025-06-05  1

How can I hide posts that are in an array of ids in the usermeta for the current user in the main query.

I can use post__not_in in meta_query but I do not know which option to use for only a specific user.

I think should use posts_where?

How can I hide posts that are in an array of ids in the usermeta for the current user in the main query.

I can use post__not_in in meta_query but I do not know which option to use for only a specific user.

I think should use posts_where?

Share Improve this question edited Dec 26, 2018 at 21:27 Alex asked Dec 26, 2018 at 20:41 AlexAlex 155 bronze badges 8
  • And what have you tried already? – Krzysiek Dróżdż Commented Dec 26, 2018 at 20:53
  • I searched the entire site but found nothing. I can not think of anything :/ – Alex Commented Dec 26, 2018 at 20:57
  • And you haven’t found this question: wordpress.stackexchange/questions/65146/… which is first result in Google for query “WordPress exclude posts from loop”? Seriously? – Krzysiek Dróżdż Commented Dec 26, 2018 at 21:00
  • 1 Possible duplicate of Exclude post ID from wp_query – Krzysiek Dróżdż Commented Dec 26, 2018 at 21:01
  • Really? The problem is that I want to hide only for the current user (logged in). – Alex Commented Dec 26, 2018 at 21:04
 |  Show 3 more comments

1 Answer 1

Reset to default 1

I'm not entirely sure what the problem is, because you've already mentioned all the tools that you need to solve it...

Just use pre_get_posts filter, check if the user is logged in, get the IDs of posts he should not see and exclude them in query:

function remove_some_posts_for_user( $query ) {
    if ( ! is_admin() && is_user_logged_in() && $query->is_main_query() ) {
        $posts_to_remove_for_current_user = get_user_meta( get_current_user_id(), 'posts_to_remove', true );
        if ( ! empty($posts_to_remove_for_current_user) is_array($posts_to_remove_for_current_user) ) {
            $query->set( 'post__not_in', $posts_to_remove_for_current_user );
        }
    }
} 
add_action( 'pre_get_posts', 'remove_some_posts_for_user' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749067121a316068.html

最新回复(0)