skip to Main Content

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


  1. Try wrap it into a function that checks whether $post_ids are empty or not.

    if (!empty($post_ids)) {
        $wp_query = new WP_Query(array(
            'post_type' => 'parvandeh',
            'post__in'  => $post_ids, 
            'posts_per_page' => 15,
            'paged' => $paged,
            'orderby'   => 'date', 
            'order'     => 'DESC'
        ));
    }
    
    Login or Signup to reply.
  2. 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…

    $params = array(
        'post_type' => 'parvandeh',
        'posts_per_page' => 15,
        'paged' => $paged,
        'orderby'   => 'date', 
        'order'     => 'DESC'
    );
    
    $post_ids = array_merge( $args_a, $args_b);
    if (!empty($post_ids)) {
        $params['post__in']  = $post_ids,;
    }
    $wp_query = new WP_Query($params);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search