1

I can't get my head around, why offset seems to be forwarded from custom WP_Query in page template to the main query further down?!

From my functions.php

/**
 * ::: Filter 'Custom Post Type' Archive Main Query :::
 */
add_action( 'pre_get_posts', 'filter_cpt_posts' );

function filter_cpt_posts( $query ) {
    if ( ! is_admin() && $query->is_main_query() && ! is_post_type_archive( 'cpt' ) ) {
        return $query;
    } 
    else { // on is_post_type_archive( 'cpt' )
        $query->set( 'offset', '1' );
        return $query;
    }
}

From my archive-cpt.php:

<?php
    $loop_recent_post = new WP_Query( array(
        'post_type' => 'cpt',
        'posts_per_page' => 1, // number of posts to display
        'offset' => 0
    ) );

    if ( $loop_recent_post->have_posts() ) {
        while ( $loop_recent_post->have_posts() ) { 
            $loop_recent_post->the_post(); 
?>

<!-- HTML Code -->

<?php wp_reset_postdata(); ?>

and further down:

<?php 
    //query_posts( 'post_type=cpt&offset=1' ); //Get rid of `query_posts`
    if ( have_posts() ) { 
        while ( have_posts() ) {
            the_post();
?>

Posts start in main query with offset=0.

Why?

PS: Yes,

1 Answer 1

1

It helps to write problems down.

After I haven't used pre_get_posts extensively, I focused too much on that area for the cause, but it was the if clause.

Changed to

if ( ! is_admin() && $query->is_main_query() && ! is_post_type_archive( 'cpt' ) ) {
    return $query;
} 
elseif ( ! is_admin() && $query->is_main_query() && is_post_type_archive( 'cpt' ) ) { // on is_post_type_archive( 'cpt' )
    $query->set( 'offset', '1' );
    return $query;
}
else {
    return $query;
}

Everything is working fine. I like pre_get_posts.

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.