从主循环中分离粘性帖子。 #WordPress

时间:2017-07-19 11:15:55

标签: php wordpress wordpress-theming

我需要你的帮助。我想从主循环(tempate:index.php)中分离粘性帖子,并希望在其余循环之前添加粘贴帖子后的内容。请看截图。这个自定义循环的任何提示?我会感激的。

屏幕截图:http://imgur.com/a/e37Pj

结构类似于:

— These are sticky posts
– sticky post one
– sticky post two
– sticky post three

++ Add something after sticky posts.
— The rest of main loop.
– normal post one
– normal post two.
– normal post three.

提前致谢。

此致 - Pomy

3 个答案:

答案 0 :(得分:0)

在索引中的标准循环之前,您可以创建区域创建要加载“粘性”帖子的位置

在帖子页面写这个

<ul>
     <?php

     global $post;
     $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 'Sticky' );

     $myposts = get_posts( $args );
     foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
       </li>
     <?php endforeach; 
     wp_reset_postdata();?>
</ul>

这将为您提供所需类别的帖子,在这种情况下,您将从“粘性”类别获得 5 帖子

答案 1 :(得分:0)

试试这个:

<?php
$args = array('posts_per_page' => 12, 'post__in' => get_option('sticky_posts'));
$stickyposts = new WP_Query($args);
while($stickyposts->have_posts()) : $stickyposts->the_post();
?>

    <!-- sticky posts (max. 12) -->

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

    <!-- -->
    <!-- here you can add random text or a horizontal line with a new headline or s.th. 
    <!-- like that. This is the exactly place between sticky and normal posts -->
    <!-- -->

<?php
$args = array('posts_per_page' => 12, 'post__not_in' => get_option('sticky_posts'));
$normalposts = new WP_Query($args);
while($normalposts->have_posts()) : $normalposts->the_post();
?>

    <!-- normal posts without sticky posts (max. 12) -->

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

这将在您的页面顶部显示12个粘贴帖子。之后,您可以输入一些随机文本,或者s.th.像那样,接着是12个“普通”帖子,这些帖子不是粘贴的帖子。

答案 2 :(得分:0)

尝试在循环中使用递增变量(即$counter++)和条件语句,以在循环通过所有(3)条粘性帖子后触发您想要的内容。

<?php
$count=0; //Count is 0 outside of loop
while ( have_posts() ) : the_post(); // Begin WP loop
if(!is_sticky()) : $count++; endif; // Start count for nonsticky loops

if(!is_sticky() && $count==1){ 
// Do stuff when the first none-sticky post is discovered inside the loop
// ie. Add a div, or insert a class name, etc.
}

// Here is an example of an actual implementation
if(!is_sticky() && $count==1): echo '<div class="not-sticky">'; endif;

// Loop countinues

endwhile; // Loop ends
if(!is_sticky(): echo '</div><!-- .not-sticky -->'; // Placed outside of loop or add inside a conditional statement within the loop to only run once
?>

...几年后,但我希望它仍然可以帮助可能面临相同问题的其他人。