Adr*_*ian 1 php wordpress loops
我在wordpress的php模板文件中使用短代码,因为短代码打开和关闭我需要将其中的整个内容作为一个变量获取.在这种情况下,内容是wordpress循环.
到目前为止,我只显示了循环的最后一个帖子.我理解为什么,因为这是变量的最终值.我想知道有人可以帮我把整个内容(即所有三个帖子)都变成一个变量,而不是最后的帖子.
谢谢
<?php 
                $news_title .= '';
                $news_single_post .= '';
            if ( have_posts() ) :
            $the_query = new WP_Query( array ( 'posts_per_page' => 3, 'cat' => 1 ) ); /*  */
             while ($the_query->have_posts() ) : $the_query->the_post(); ?>
            <?php 
                $news_title = get_the_title();
                $news_excerpt = get_the_excerpt();
                $news_single_post = '<div class="home-content-news-title">'.$news_title.'</div><div class="home-content-news-excerpt">'.$news_excerpt.'</div>';
                endwhile;
                wp_reset_postdata();
                endif; 
                $news_tab_title_string = 'News';
                $news_tab_title_shortcode = do_shortcode('[wptabtitle]'.$news_tab_title_string.'[/wptabtitle]');
                $news_tab_content_shortcode = do_shortcode('[wptabcontent]'.$news_single_post.'[/wptabcontent]');
                $news_tab = $news_tab_title_shortcode.$news_tab_content_shortcode;
                echo do_shortcode('[wptabs]'.$news_tab.'[/wptabs]');
         ?>
Run Code Online (Sandbox Code Playgroud)
    定义您希望所有内容进入循环上方和外部的$variable = '';变量,例如,然后在循环内使用该变量连接到该变量$variable .= $content_to_concat;,然后echo $variable;在末尾使用循环外部来打印整个内容.
您的代码作为示例:
<?php 
    $news_title .= '';
    $news_single_post .= '';
    $news_all_posts = ''; // Define the variable
    if ( have_posts() ) :
    $the_query = new WP_Query( array ( 'posts_per_page' => 3, 'cat' => 1 ) ); /*  */
    while ($the_query->have_posts() ) : $the_query->the_post();
    $news_title = get_the_title();
    $news_excerpt = get_the_excerpt();
    $news_single_post = '<div class="home-content-news-title">'.$news_title.'</div><div class="home-content-news-excerpt">'.$news_excerpt.'</div>';
    $news_all_posts .= $news_single_post; // Add each post to the variable
    endwhile;
    wp_reset_postdata();
    endif;
    $news_tab_title_string = 'News';
    $news_tab_title_shortcode = do_shortcode('[wptabtitle]'.$news_tab_title_string.'[/wptabtitle]');
    // Use the variable to display the content
    $news_tab_content_shortcode = do_shortcode('[wptabcontent]'.$news_all_posts.'[/wptabcontent]');
    $news_tab = $news_tab_title_shortcode.$news_tab_content_shortcode;
    echo do_shortcode('[wptabs]'.$news_tab.'[/wptabs]');
 ?>
Run Code Online (Sandbox Code Playgroud)