在foreach循环中发布标题不正确,但内容正确-Wordpress

时间:2020-02-21 14:54:16

标签: php wordpress plugins

function quotes_shortcode() {
    if ( false === ( $quotes = get_transient( 'random_quote' ) ) ) {
        // It wasn't there, so regenerate the data and save the transient

        $args = array(
         'post_type' => 'quotes',
         'orderby'   => 'rand',
         'fields' => 'id',
         'posts_per_page' => '1'
        );

        $quotes = get_posts( $args );
        //Now we store the array for one day.
        //Just change the last parameter for another timespan in seconds.
        $seconds_until_next_day = strtotime('tomorrow') - time();
        set_transient( 'random_quote', $quotes, MINUTE_IN_SECONDS );
    }

        foreach ( $quotes as $posts ) : setup_postdata( $posts );
        ?>  
        <div class="quote_container">

            <em><?php the_content(); ?> - <p><?php the_title(); ?></p></em>
        </div>  
        <?php 
        endforeach;
    wp_reset_postdata();
}
add_shortcode('random_quotes','quotes_shortcode');

我创建了一个wordpress短代码来每天显示随机报价,报价的内容似乎显示良好,但标题不正确,因为它正在获取插入了简码的页面或帖子的标题。

2 个答案:

答案 0 :(得分:2)

您需要使用<?php echo $post->post_title; ?>来显示正确的标题。

答案 1 :(得分:0)

与文档中一样:

setup_postdata()分配全局$ post变量,因此您必须自己执行此操作很重要。否则,任何将上述全局变量与$ post全局变量结合使用的钩子都会引起问题,因为它们将引用单独的实体。

所以试试这个:

function quotes_shortcode() {
    if ( false === ( $quotes = get_transient( 'random_quote' ) ) ) {
        // It wasn't there, so regenerate the data and save the transient

        global $post; // Calls global $post variable

        $args = array(
         'post_type' => 'quotes',
         'orderby'   => 'rand',
         'fields' => 'id',
         'posts_per_page' => '1'
        );

        $quotes = get_posts( $args );
        //Now we store the array for one day.
        //Just change the last parameter for another timespan in seconds.
        $seconds_until_next_day = strtotime('tomorrow') - time();
        set_transient( 'random_quote', $quotes, MINUTE_IN_SECONDS );
    }

        foreach ( $quotes as $quote ) : 

            $post = $quote; // Set $post global variable to the current post object

            setup_postdata( $post );
        ?>  
        <div class="quote_container">

            <em><?php the_content(); ?> - <p><?php the_title(); ?></p></em>
        </div>  
        <?php 
        endforeach;
    wp_reset_postdata();
}
add_shortcode('random_quotes','quotes_shortcode');