【问题标题】:Wordpress show the_content grabs wrong post's content. Why?Wordpress 显示 the_content 抓取错误的帖子内容。为什么?
【发布时间】:2012-12-29 16:29:36
【问题描述】:

我的问题是我正在显示“事件”类别中的一些帖子。然后稍后在同一页面上,我想显示来自“spiller”类别的随机帖子,并且效果很好。它得到一个随机帖子,显示标题、缩略图,但是当我说显示 the_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>

【问题讨论】:

    标签: php html wordpress thumbnails customizing


    【解决方案1】:

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

    请考虑将 query_posts 替换为 WP_Query。

    除此之外,您还需要重置您的 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,您需要能够在运行中再次更改它。

    重置您的查询只是确保所有全局变量都恢复为 Wo​​rdpress 默认值的良好常规做法。但是 setup_postdata($post_object) 实际上允许我们在自定义循环中将 Global 更改为当前对象。

    WP_Query 如此有效的原因是重置查询不再是必需的,因为 WP_Query 循环已本地化到该特定对象,并且不会修改全局 $wp_query(这会顺便影响许多其他全局变量)。

    这里有一些关于query_posts vs WP_Query 的方便信息,应该可以更好地为您解释。

    这有帮助。

    【讨论】:

    • 谢谢,非常详细,我会仔细阅读您所说的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    相关资源
    最近更新 更多