添加heredoc后自定义post WpQuery foreach循环仅返回一个结果

我已经为这个问题摸不着头脑一两天了。我正在尝试让 WordPress 使用调用functions.php. 我设法使代码正常工作,但它打印到页面顶部,因为我认为echo默认情况下是 PHP ,而我需要这样做return。另一个问题是,目前它只打印单个最新结果。在我开始使用之前,循环就可以工作,HEREDOC但我想我需要使用它来返回而不是 echo。


代码:


add_shortcode('recentvideos' , 'printrecenttv');


function printrecenttv(){

    $recent_posts = wp_get_recent_posts(array(

        'numberposts' => 4, // Number of recent posts thumbnails to display

        'post_status' => 'publish', // Show only the published posts

        'post_type'  => "tv" //Show only Videos

    ));

    foreach($recent_posts as $post) : 

        $perm = get_permalink($post['ID']);

        $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');

return <<<HTML

     <div class="videoposter">

        <a class="posterlink" href="$perm">

                <img class="posterimg" src="$imgurl">

            </a>

    </div>

HTML;

     endforeach; wp_reset_query();

}

我究竟做错了什么?


侃侃尔雅
浏览 117回答 1
1回答

炎炎设计

您的代码中的问题是返回。return返回值并停止进一步的代码执行,这意味着return之后的所有代码都不会运行。您启动 foreach,运行代码并使用 return,将heredoc 传递给 return(循环的第一次迭代),就是这样,return 停止所有进一步的代码执行。您需要在循环外创建一个变量,假设$html = '';每次迭代都连接您需要的 html。foreach 完成后,您可以检查是否$html不为空,然后返回$html$html = '';foreach ($recent_posts as $post) {&nbsp; &nbsp; $perm&nbsp; &nbsp;= get_permalink($post['ID']);&nbsp; &nbsp; $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');&nbsp; &nbsp; $html .= '<div class="videoposter">';&nbsp; &nbsp; $html .=&nbsp; &nbsp;'<a class="posterlink" href="' . $perm . '">';&nbsp; &nbsp; $html .=&nbsp; &nbsp; &nbsp;'<img class="posterimg" src="' . $imgurl . '">';&nbsp; &nbsp; $html .=&nbsp; &nbsp;'</a>';&nbsp; &nbsp; $html .= '</div>';}if (!empty($html)) {&nbsp; return $html;}如果你愿意的话,你当然可以使用heredoc。希望这有帮助=]
打开App,查看更多内容
随时随地看视频慕课网APP