How do you Query posts with nothing in common?

We can get multiple posts manually in a page, but that’s generated in a template, AFTER the default query returned something else (page/post, etc)

How do you query multiple posts in a public query, which share no taxonomy or anything else?

Read More

e.g. by ID:

http://example.com/?p=23,18,2,199,6,8

I got it working already parsing a variable in a page-name.php template, but once it gets the template it’s too late to generate e.g. canonicals.

I guess this would be something similar to a search, except the search is a 1-to-multiple-posts relation and this requires a multiple-queries-to-unique-post (each).

Thanks.

Related posts

Leave a Reply

2 comments

  1. Maybe you’re looking for the post__in parameter in WP_Query.

    $query = new WP_Query(array(
        'post__in' => array(23,18,2,199,6,8)
    );
    

    And then:

    while ( $query->have_posts() ) {
        $query->the_post();
        /* post loop */
    }
    

    Take a look at the docs. =D

    For public queries:

    post__in is not public queryable by default, so you can just validate and copy $_GET['post__in'] on the parse_query action hook, and let the thing happen.

    add_action('parse_query', 'wpse59828_parse_query');
    function wpse59828_parse_query($query) {
        if (empty($_GET['post__in']))
            return $query;
    
        $posts = explode(',', $_GET['post__in']);
        $post__in = array();
        foreach ($posts as $p) {
            $post__in[] = intval($p);
        }
    
        $query->query_vars['post__in'] = $post__in;
        return $query;
    }
    

    Then you would just access this:

    http://mywebsite.com/?post__in=23,18,2,199,6,8
    

    Please note that, like this, you won’t be able to set the post order in WordPress versions before 3.5 (#13729). Use this plugin if you need to.

  2. $tax_query = array (
        array (
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $cat_name
            )
        );
    
    $args = array( 'tax_query' => $tax_query, 'numberposts' => -1);
    $lastposts = get_posts( $args );