1

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 =(

  • I think you want an array of user id's that are attached as custom field to those posts. Then you will check for user is in array of touched id's. Second, I am not sure that the order in the OR relation matters. But I suggest test first if not exists and later if not equal to. – Mulli May 28 '22 at 03:35
  • Well, I've found some solution. But it's not quite nice. Just to modify SQL request with `posts_where` filter ([details](https://wp-kama.ru/hook/posts_where)) and adding `" AND ID NOT IN (SELECT post_id FROM wp_postmeta WHERE meta_key='users_touched_ids' AND meta_value='". $user_id ."')"`. Hope it'll help somebody =) – Kostya Grul Jun 03 '22 at 02:08

1 Answers1

0

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 );

Titus
  • 784
  • 2
  • 13
  • I'm not quering for posts that was created by user but for posts those ones that was NOT "touched" by him/her. It's not very important users ids it, or something else. The problem could be generalized like this: Posts have some meta field with a lot of different values for each post (meta_field is not single). I need to select posts, that doesn't have some specified value of that field. – Kostya Grul May 28 '22 at 14:32