Insert/sticky specific post into Loop at specific location

This took a bit of trial and error but I think I got it. I was getting an infinite loop until I added suppress_filters. After that it was short work.

function insert_post_wpse_96347($posts) {
  global $wp_query;
  $desired_post = 151;
  if (is_main_query() && is_home() &&  0 == get_query_var('paged')) {
    $p2insert = new WP_Query(array('p'=>$desired_post,'suppress_filters'=>true));
    $insert_at = 3;
    if (!empty($p2insert->posts)) {
      array_splice($posts,$insert_at,0,$p2insert->posts);
    }
  }
  return $posts;
}
add_filter('posts_results','insert_post_wpse_96347');

This will force a post, which I have hard-coded, into position 3, again hard-coded. I don’t know how you are saving, or plan to save, your configuration values but that is is the basic “insert” function. This will increase the post count for the first page above the configured value but otherwise preserves normal pagination as far as I can tell. It is tested but barely.

Leave a Comment