Offset Specific Category from Main Loop
-
My goal is for my main blog page to have a slider of three posts from the Featured category. However, I don’t want to duplicate these posts in the main feed below.
This is my attempt:
In my main blog page, I have two separate loops. The first is a custom WP_Query that gets the most recent 3 posts from the Featured Category (I will be turning this into a slider which is irrelevant here). It looks like this…
<?php $args = array( 'post_type' => 'post', 'category_name' => 'featured', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page'=> '3', ); $featured_posts= new WP_Query($args); if($featured_posts->have_posts()) : while($featured_posts->have_posts()) : $featured_posts->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; endif; ?>Then, I run my normal query to get all the posts. It looks like this…
<?php if(have_posts()) : while(have_posts()) : the_post(); ?> --Do something-- <?php endwhile; endif; ?>Finally, in my functions.php file, I have the following function that hooks into “pre_get_posts” action hook to offset my main query by 3. It looks like this:
function wpsites_exclude_latest_post($query) { if ($query->is_home() && $query->is_main_query()) { $query->set( 'offset', '3' ); } } add_action('pre_get_posts', 'wpsites_exclude_latest_post');Everything is almost working except I want to only offset those posts from the “featured” category so they move from the slider and then down into the main loop and never duplicate. How can I offset the main query by three but only from the featured category? Am I going about this the correct way?
The topic ‘Offset Specific Category from Main Loop’ is closed to new replies.