【问题标题】:Custom post WpQuery foreach loop only returning one result after heredoc added添加heredoc后自定义post Wp_Query foreach循环仅返回一个结果
【发布时间】:2020-11-02 12:39:12
【问题描述】:

我已经为这个问题挠头一两天了。我试图让 WordPress 使用调用functions.php 中的函数的简码打印所有最近的帖子。我设法让代码工作,但它打印到页面顶部,因为我认为 PHP echos 默认情况下我需要 return。另一个问题是目前它只打印一个最近的结果。在我开始使用 HEREDOC 之前,循环正在工作,但我认为我需要使用它来返回而不是回显。

代码:

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();
}

我做错了什么?

【问题讨论】:

    标签: php wordpress foreach heredoc


    【解决方案1】:

    您的代码中的问题是返回。

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

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

    您需要在循环之外创建一个变量,比如说$html = '';,并且每次迭代都会连接您需要的 html。 foreach 完成后,您可以检查$html 是否不为空,然后返回$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。

    希望这会有所帮助 =]

    【讨论】:

    • 啊 - 这更有意义!非常感谢!
    • 我应该补充一下 - 我确实必须将 html .= 更改为 $html .=
    猜你喜欢
    • 2020-05-06
    • 2014-10-26
    • 2016-03-01
    • 2021-09-24
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2013-12-15
    相关资源
    最近更新 更多