Add few specific post ids to wp_query

I have following args to get recent posts,

$args = array(
    'date_query' => array( array( 'after' => '1 week ago' ) ),  
    'posts_per_page' => 15,
    'ignore_sticky_posts' => 1,
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'cat' => '-907,-908,-909'
);

Now I need include few specific Ids to same query. So I tried follows, but it doesn’t work

$highlights = array('8308', '8315');

$args = array(
    'date_query' => array( array( 'after' => '1 week ago' ) ),  
    'posts_per_page' => 15,
    'ignore_sticky_posts' => 1,
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'cat' => '-907,-908,-909',
    'post__in' => $highlights
);

Now it just giving me those two posts.

3 Answers
3

Here is another way of doing it, specially if you need to work with the query object. The issue with merging queries is that you loose the correctness of the query object.

My idea here is to run two separate queries, one very lean one to get post ID’s from the date_query query and then merging the two arrays of post ID’s and then pass those ID’s to proper WP_Query query.

(NOTE: This code requires at least PHP 5.4)

$highlights = [8308, 8315];

$args = [
    'date_query'          => [
        [
            'after'       => '1 week ago' 
        ]
    ],
    'posts_per_page'      => 13,
    'meta_key'            => 'post_views_count',
    'orderby'             => 'meta_value_num',
    'order'               => 'DESC',
    'cat'                 => '-907,-908,-909',
    'post__not_in'        => $highlights,
    'fields'              => 'ids' // ONLY GET POST ID's, VERY LEAN QUERY
];
$q = get_posts( $args );

$merged_ids = array_merge( $highlights, $q );

Note now, the hightlights are in front of the query, and the posts from $q is ordered by date. If you need to retain this order, simply add 'orderby' => 'post__in', to the arguments of the query below

if ( $merged_ids ) {
    $args_final = [
        'post__in'            => $merged_ids,
        'posts_per_page'      => -1,
        'orderby'             => 'post__in',
        'ignore_sticky_posts' => 1
    ];
    $query_final = new WP_Query( $args_final );

    // Run your loop
}

Leave a Comment