I have a code for WordPress that suppose to get ID of posts with two conditions (args) with get_posts
then using WP_Query
to list posts by those IDs.
Here is my code:
<?php
$user_id = get_current_user_id();
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args_a = get_posts(array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => array('parvandeh'), 'author' => $user_id ));
$args_b = get_posts(array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => array('parvandeh'), 'meta_query' => array(
array(
'key' => 'parbandeh_masool',
'value' => $user_id,
),
), ));
$post_ids = array_merge( $args_a, $args_b);
$wp_query = new WP_Query(array(
'post_type' => 'parvandeh',
'post__in' => $post_ids,
'posts_per_page' => 15,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
));
?>
In this code I have two args $args_a
and $args_b
.
This code works fine if even one of the args find any ID, but when none of those args couldn’t find any IDs, This code just show all posts!
I want to avoid it to list all posts if it doesn’t found any ID with $args_a
and $args_b
. What is wrong with this code and how can I fix it? Thanks
2
Answers
Try wrap it into a function that checks whether $post_ids are empty or not.
If you extract the query parameters to before the call, you can add in the
post__in
part of the query if there are any…