Неправильный заголовок сообщения в foreach l oop, но содержание правильное - Wordpress - PullRequest
0 голосов
/ 21 февраля 2020
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 ]

2 голосов
/ 03 мая 2020

Вам нужно использовать <?php echo $post->post_title; ?>, чтобы показать правильный заголовок.

0 голосов
/ 21 февраля 2020

Как и в документации:

setup_postdata () не не присваивает глобальную переменную $ post, поэтому важно, чтобы вы сделали это самостоятельно. Невыполнение этого требования приведет к проблемам с любыми хуками, которые используют любой из вышеперечисленных глобалов в сочетании с $ post global, поскольку они будут ссылаться на отдельные сущности.

Так попробуйте это:

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');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...