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

Custom post WpQuery foreach loop only returning one result after heredoc added

我已经为这个问题绞尽脑汁一两天了。我试图让 WordPress 使用调用 functions.php 中的函数的短代码打印所有最近的帖子。我设法让代码工作,但它打印到页面顶部,因为我假设默认情况下 PHP echos 而我需要 return。另一个问题是目前它只打印最近的单个结果。在我开始使用 HEREDOC 之前,循环一直在工作,但我认为我需要将其用于 return 而不是 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();
}

我做错了什么?

您的代码中的问题是 return。

return returns 值并停止进一步的代码执行,这意味着 return 之后的所有代码都不会 运行.

你开始你的 foreach,运行 代码并使用 return,你将 heredoc 传递给 return(循环的第一次迭代)就是这样,return 停止所有进一步的代码执行。

您需要在循环外创建一个变量,比方说 $html = ''; 并且每次迭代连接您需要的 html。 foreach 完成后,您可以检查 $html 是否不为空,然后 return $html

$html = '';

foreach ($recent_posts as $post) {
    $perm   = get_permalink($post['ID']);
    $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');

    $html .= '<div class="videoposter">';
    $html .=   '<a class="posterlink" href="' . $perm . '">';
    $html .=     '<img class="posterimg" src="' . $imgurl . '">';
    $html .=   '</a>';
    $html .= '</div>';
}

if (!empty($html)) {
  return $html;
}

如果你愿意,当然可以使用heredoc。

希望这对您有所帮助 =]