在顶部显示Sticky Posts但在循环中不再显示这些帖子?

时间:2015-07-16 00:47:29

标签: wordpress

关于wordpress.org

对于我主页上的主循环,我想在顶部显示粘贴帖子但是我不希望帖子再次出现在循环中,否则对访问者来说似乎是多余的。

以下代码的问题是他们从顶部删除粘贴帖子 我想保留顶部的粘贴帖子 但是从循环中删除/排除它。这可能吗?

代码A:这会从顶部删除粘贴帖子

function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'ignore_sticky_posts', true );
    }
}
add_action( 'pre_get_posts', 'mango' );

代码B:这将从顶部AND循环中移除粘性帖子

function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'post__not_in', get_option( 'sticky_posts' ) );
    }
}
add_action( 'pre_get_posts', 'mango' );

1 个答案:

答案 0 :(得分:0)

我认为你必须为此创建两个循环。一个用于粘贴帖子,一个用于常规帖子(但排除来自第二个循环的粘性帖子)。显然,您必须将此代码放入 index.php 。没有测试它,但我认为应该这样做......

<?php //we will get "Sticky Posts" only with this loop 

    $sticky = get_option( 'sticky_posts' );

     $args = array(
    /* Add whatever you need here - see http://codex.wordpress.org/Class_Reference/WP_Query */
    'post__in'  => $sticky,     
     );

$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );

if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post();
if ( empty( $sticky ) ) break;  
?>

<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
<?php endwhile; ?>
<?php endif; ?><!--END if THE LOOP-->

<?php //Exlude stickies from second loop...
    $sticky = get_option( 'sticky_posts' );  
    $args = array(  
    'post__not_in'  => $sticky,
    );

$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );

if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php endwhile; ?>
<?php endif; ?><!--END if THE LOOP-->

<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
相关问题