2017-10-05 99 views
0

我有一个短代码应该返回单个页面上多个自定义帖子的标题和内容。它正确显示每篇文章的标题,但是当显示每篇文章的内容时,它只会显示第一篇文章的内容。我究竟做错了什么?弄清楚如何从简码中获取内容已经非常棘手,所以如果任何人有任何建议,我会很感激!循环中的do_shortcode仅返回第一个帖子的内容

我的代码是:

if($customposts->have_posts()) : while ($customposts->have_posts()) : $customposts->the_post(); 
    $post= get_the_ID(); 
    $foo = get_the_title(); 
    $bar=do_shortcode($content); 
    echo "<h2>".$foo."</h2><p>".$bar."</p>";  


endwhile; endif;  
+0

我猜测$内容是在循环外部设置的,因此你总是得到相同的结果。 – janh

+0

它在我的短代码函数中设置在此循环外部。 – bjorkland

+0

'$ content'是什么? – Spartacus

回答

0

它看起来并不像你需要给我们do_shortcode。如果title工作正常,您应该能够将get_the_content()分配给您的$bar变量。

$bar = get_the_content(); 
0

既然你通过帖子循环,存储从循环的每次迭代的HTML,然后返回所有的HTML一次(记住,你不能呼应或从短码回调打印.. 。好了,你不应该,否则你会得到一些意想不到的结果):

$html = ''; 
    if($customposts->have_posts()) : 
     while ($customposts->have_posts()) : $customposts->the_post(); 
     $post= get_the_ID(); 
     $foo = get_the_title(); 
     $bar = get_the_content(); 
     $html .= "<h2>$foo</h2><p>$bar</p>"; 
    endwhile; endif; 

return $html; 

此外,要小心使用$post作为自己的变量,你肯定会接触到其他脚本冲突,包括核心。

+0

我正在使用短代码..这个循环在我的短代码函数中。在简码中使用the_content()也会导致致命错误。 – bjorkland

+0

我完全误解了你的意图。我编辑了我的答案。 – Spartacus

相关问题