I need to get custom posts with next conditions:
- Custom post with meta
'key1' => 'public'
- Custom post with meta
'key1' => 'private'
and'author' => 'current_user_id'
Code:
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'meta_key' => 'key1',
'meta_value' => 'public'
);
$args2 = array(
'post_type' => $post_type,
'posts_per_page' => -1,
'meta_key' => 'key1',
'meta_value' => 'private',
'author' => get_current_user_id()
);
$get_posts = new WP_Query($args);
$custom_posts = $get_posts->get_posts();
$get_posts_2 = new WP_Query($args2);
$custom_posts2 = $get_posts_2->get_posts();
and then I merge them:
$merged_posts = array_merge($custom_posts2, $custom_posts2);
It works, but I have problem with pagination and total items count. And it is two query instead of one.
How can I achieve this with a single query?
So from my understanding:
IF > User not Logged In – Show all ‘Public’ (meta) posts.
ELSE IF > User Logged In – Show all ‘Public’ (meta) posts (from all users) AND all ‘Private’ (meta) posts from the current logged in user.
I’ve run two queries below and combined the posts. It’s not without flaws, for instance: On the first page it shows more than
posts_per_page
parameter. I also couldn’t manually override the defaultposts_per_page
without breaking pagination.You may need to save out permalinks to get this to work – hopefully it does!