I would like to add a post (from specific category) between posts in the WordPress Loop (such as ‘Sponsors’). Example:
P P P S
P P S P
P S P P
How can I achieve this? I am a beginner with coding, so I don’t know enough to modify a Loop on my own. Any Loop Coding Ninjas out there that can provide a solution?
Note that below is my current Loop. It is used to sort posts by price, or by random order:
index.php
<?php while (have_posts() ) : the_post(); ?>
<h2><a href="https://wordpress.stackexchange.com/questions/158133/<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); the_meta ();
endwhile;
previous_posts_link();
next_posts_link();
?>
functions.php
function my_custom_query($query){
if ( $query->is_home() && $query->is_main_query() ) {
$sort= $_GET['sort'];
if($sort == "A"){
$query->set( 'orderby', 'rand' );
$query->set( 'posts_per_page', '2' );
}
if($sort == "B"){
$query->set( 'meta_key', 'price' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
$query->set( 'posts_per_page', '2' );
}
}
}
add_action( 'pre_get_posts', 'my_custom_query' );
Edit: Update
Birgire’s plugin works! Initially, I had problems getting the plugin to work on my theme. The problem was this piece of code that I use within the Loop in index.php (I use it to call for the custom field to appear).
<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'price', true);
wp_reset_query();
?>