Wordpress显示the_content抓取错误帖子的内容。为什么?

时间:2013-01-15 14:37:24

标签: php html wordpress thumbnails customizing

我的问题是我正在显示“事件”类别中的一些帖子。然后稍后在同一页面上,我想显示一个来自“spiller”类别的随机帖子,并且工作正常。它会随机发布一个帖子,显示标题,缩略图,但是当我说show_content(或the_excerpt)时,它会显示“事件”类别中帖子的所有内容(或摘录)。请帮帮我解决这个问题!

<div class="well span6 Padding10">
    <h4 class="titleFont MarginBottom20">KOMMENDE BEGIVENHEDER</h4>
    <?php
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $args  = array(
        'category_name' => 'events', // Change these category SLUGS to suit your use.
        'paged'         => $paged

    );
    query_posts( $args ); ?>
    <ul>
        <?php
        while ( have_posts() ) : the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><strong><?php the_title(); ?></strong></a>
            </li>
        <?php endwhile; ?>
    </ul>
</div>

<div class="span6 well" style="height: 250px;"><h4 class="titleFont">SPILLER HIGHLIGHT</h4>
    <div class="row-fluid">
        <?php
        $args       = array(
            'numberposts'   => 1,
            'orderby'       => 'rand',
            'category_name' => 'spiller'
        );
        $rand_posts = get_posts( $args );
        foreach ( $rand_posts as $post ) : ?>

            <div class="span5"><?php the_post_thumbnail( array( 150, 150 ) ); ?></div>
            <div class="span6 MarginTop10">
                <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                <!-- THIS IS WHERE IT MESSES UP: --><?php the_content(); ?>
            </div>
        <?php endforeach; ?>
    </div>
</div>

1 个答案:

答案 0 :(得分:6)

首先,您需要避免使用query_posts。它会影响很多Wordpress Globals,并改变默认循环 - 除非这是你的特定意图 - 绝对需要避免,因为它也可能导致性能问题。

请考虑用WP_Query代替query_posts。

除此之外,您需要重置postdata,并在下一个循环中设置新的postdata。

重置查询:

<?php 
while ( have_posts() ) : the_post(); 
?>
<li>
    <a href="<?php the_permalink(); ?>"><strong><?php the_title(); ?></strong></a>
</li>

<?php endwhile;wp_reset_query(); ?>

设置:

foreach( $rand_posts as $post ) : setup_postdata($post); ?>

重置Postdata:

<?php endforeach;wp_reset_postdata(); ?>

为什么需要这样做?

无论何时使用前缀为“the_”的便捷Wordpress功能,该功能都会引用$ post Global。 query_posts更改Global(如上所述),如果您计划在单独的循环中引用该Global,则需要能够动态地再次更改它。

重置查询只是确保所有Globals都回到Wordpress默认值的一般做法。但是setup_postdata($ post_object)实际上允许我们将Global更改为自定义循环中的当前对象。

WP_Query之所以如此有效,是因为重置查询不再必不可少,因为WP_Query循环已本地化到该特定对象,并且不会修改Global $ wp_query(这会偶然影响很多其他全局变量)。

这里有一些关于query_posts vs WP_Query的方便信息,可以为你解释一些更好的事情。

跳这有帮助。

相关问题