WP_QUERY、PRE_GET_POST和OFFSET

时间:2015-03-06 作者:Volker E.

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 个回复
SO网友:Volker E.

它有助于把问题写下来。

在我没有使用pre_get_posts 从广泛的角度来看,我过于关注这一领域的原因,但这是if 条款

更改为

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;
}
一切正常。我喜欢pre_get_posts.

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post