Search code examples
phpwordpresswordpress-themingcustom-wordpress-pages

Wordpress how to use two variables for Post__not_in argument in a wp_query


How can I put two variables in post__not_in like this:

'post__not_in' => $excludeHome, $excludePostSlide

When I do this only posts from first variable don't show up from the others show up.

I can do that with array push like below but is there any different way to do it?

  @php
    wp_reset_postdata();
    global $excludeHome;
    global $excludePostSlide;
    array_push($excludeHome, $excludePostSlide[0], $excludePostSlide[1], $excludePostSlide[2], $excludePostSlide[3], $excludePostSlide[4], $excludePostSlide[5]);
    $args = [
        'post_type' => 'post',
        'orderby' => 'date',
        'category_name' => 'auto',
        'posts_per_page' => 6,
        'no_found_rows' => true,
        'post__not_in' => $excludeHome,
    ];
    $querySlider = new WP_Query($args);
  @endphp

Solution

  • According to the wp_queryDocs, post__not_in accepts an array of post ids.

    • It's not clear that your global $excludeHome and $excludePostSlide variables are actually arrays. So make sure that they are arrays.
    • In order to use array_push function, it's better to use a foreach loop on the $excludePostSlide array, rather than trying to push them by their index number!
    global $excludeHome;
    global $excludePostSlide;
    
    $excludeHome = is_array($excludeHome)
        ? $excludeHome
        : (array)$excludeHome;
    
    $excludePostSlide = is_array($excludePostSlide)
        ? $excludePostSlide
        : (array)$excludePostSlide;
    
    foreach ($excludePostSlide as $excludeSlide) {
        array_push($excludeHome, $excludeSlide);
    }
    
    $args = [
        'post_type'      => 'post',
        'orderby'        => 'date',
        'category_name'  => 'auto',
        'posts_per_page' => 6,
        'no_found_rows'  => true,
        'post__not_in'   => $excludeHome,
    ];
    
    $querySlider = new WP_Query($args);