0

How can I always include a post/ page in the random result?

For instance, I always want to get 3 items only from my articles. But I want the result always has the article with page order 1:

    $parent = $post->ID;
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $query_args = array(
      'post_type' => 'page',
      'posts_per_page' => 3,
      'orderby'   => 'rand',
      'post_parent' => $parent,
      'paged' => $paged
    );

    // create a new instance of WP_Query
    $the_query = new WP_Query( $query_args );

So the result will be:

1, 2, 3, or 2, 1, 4, or 4, 2, 1

Is it possible? Does WordPress has any defaults for this?

1 Answer 1

1

Try this code::

post__in (array) - use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not.

<?php
    $parent = $post->ID;
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $query_args = array(
      'post_type' => 'page',
      'post_in' => array('post_id_to_include'),
      'posts_per_page' => 3,
      'orderby'   => 'rand',
      'post_parent' => $parent,
      'paged' => $paged
    );

   // create a new instance of WP_Query
   $wp_query = new WP_Query($query_args);
?>
6
  • thanks. how can i find the post id by page order?
    – Run
    Commented Apr 28, 2017 at 7:49
  • You want result in exact pattern 1, 2, 3, or 2, 1, 4, or 4, 2, 1
    – BlueSuiter
    Commented Apr 28, 2017 at 8:22
  • yes in all of these patterns. as long as 1 is in the result. then randomise them.
    – Run
    Commented Apr 28, 2017 at 8:53
  • I found the key myself now. but 'post_in' => array('post_id_to_include'), does not work.
    – Run
    Commented Apr 28, 2017 at 9:06
  • @BlueSuiter post_in should be post__in with two underscores, not one - in description its right but in code its wrong Commented Jul 20, 2020 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.