【问题标题】:Wordpress functions not available in templateWordpress 功能在模板中不可用
【发布时间】:2014-09-12 09:42:06
【问题描述】:

我正在编辑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> 

顺便说一句,the_ID 函数正在运行并正确输出帖子的 ID。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    在循环的每次迭代中,您需要“设置”发布数据,您可以使用 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> 
    

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多