Wordpress功能在模板中不可用

时间:2014-09-12 09:42:06

标签: php wordpress

我正在编辑front-page.php,我使用get_posts()来输出帖子。 使用the_post的其他方式无效。所以我需要输出摘录,但$ post-> post_excerpt为空,the_excerpt函数什么都不做。我不明白为什么,因为没有错误。这是代码:

<?php

    foreach ( get_posts() as $post ) { ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class('article-item well'); ?>>
            <h2 class="title text-primary">
                <a href="<?php echo $post->guid; ?>">
                    <?php echo $post->post_title; ?>
                </a>
            </h2>
            <p class="article-info text-center">
            <span class="date">Posted on <time pubdate="" title="12:19 pm" datetime="<?php echo $post->post_date; ?>" class="time">
                    <?php echo $post->post_date; ?>
                </time>
            </span>
            </p>
            <?php if (has_post_thumbnail()) { ?>
                <figure class="img-wrap">
                    <?php the_post_thumbnail('full'); ?>
                    <figcaption class="label label-primary">
                        <?php foreach((get_the_category()) as $category) {
                            echo $category->cat_name . ' ';
                        } ?>
                    </figcaption>
                </figure>
            <?php } ?>
            <p>
                <?php the_excerpt(); ?>
            </p> 

BTW the_ID功能正常工作并正确输出帖子的ID。

1 个答案:

答案 0 :(得分:3)

在循环的每次迭代中,您需要设置&#39;发布数据,您可以使用setup_postdata( $post );

执行此操作

修改您的代码如下:

<?php

foreach ( get_posts() as $post ) { 
    setup_postdata( $post );
    ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class('article-item well'); ?>>
        <h2 class="title text-primary">
            <a href="<?php echo $post->guid; ?>">
                <?php echo $post->post_title; ?>
            </a>
        </h2>
        <p class="article-info text-center">
        <span class="date">Posted on <time pubdate="" title="12:19 pm" datetime="<?php echo $post->post_date; ?>" class="time">
                <?php echo $post->post_date; ?>
            </time>
        </span>
        </p>
        <?php if (has_post_thumbnail()) { ?>
            <figure class="img-wrap">
                <?php the_post_thumbnail('full'); ?>
                <figcaption class="label label-primary">
                    <?php foreach((get_the_category()) as $category) {
                        echo $category->cat_name . ' ';
                    } ?>
                </figcaption>
            </figure>
        <?php } ?>
        <p>
            <?php the_excerpt(); ?>
        </p>