简体   繁体   中英

WP meta_query to get posts without some specific value when meta_filed is multiply

Can't find a solution how to query posts without some specific value of meta_field that have many values.

The situation is: I'm adding user id's on posts when they perform some specific operation. Like this: add_post_meta($_POST['post_id'], 'users_touched_ids', $current_user->ID);

After that I have to display to user posts that wasn't "touched" by him. So I'm writing query like this:

[
    'relation' => 'OR',
    [
        'key' => 'users_touched_ids',
        'compare' => '!=',
        'value' => $user_id
    ],
    [
        'key' => 'users_touched_ids',
        'compare' => 'NOT EXISTS',
    ],
]

But it doesn't work. I'm getting all posts =(

You getting all posts, while you query posts where users_touched_ids not equals to $user_id . This means, you get all posts where the database field users_touched_ids not contains the $user_id variable.

in case, the Author is the same as the "touch" user, you can filter the query by author like this:

$args = array(
    'author'        =>  $user_id
    'orderby'       =>  'post_date',
    'order'         =>  'ASC',
    'posts_per_page' => 1,
    'meta_query' => [
        [
        'key' => 'users_touched_ids',
        'compare' => 'NOT EXISTS',
        ]
    ]
);

$posts = get_posts( $args );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM