【问题标题】:WordPress loop that lists titles and content separately分别列出标题和内容的 WordPress 循环
【发布时间】:2015-10-20 08:07:07
【问题描述】:

我是 wordpress 新手,想创建一个循环,在左侧 div 中列出帖子标题(仅来自一个类别),在右侧 div 中列出相同帖子的内容。这就是我所做的,我想知道是否有更好的方法(嗯,可能有)?谢谢!

<div class="container">
<div class="post_title">
    <?php query_posts('cat=6'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <h3><?php the_title(); ?></h3>
    <?php endwhile; endif; ?>
    <?php rewind_posts(); ?> 
</div>          
<div class="post_content">
    <?php query_posts('cat=6'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php the_content(); ?>
    <?php endwhile; endif; ?>
    <?php wp_reset_query(); ?>
</div>                                            

【问题讨论】:

  • 永远不会使用query_posts。它很慢,会破坏主查询并破坏页面功能。您可以在 one 查询中完成所有操作。几个月前我做过类似的事情,虽然我不记得在哪里。

标签: php html loops wordpress


【解决方案1】:

改用 get_posts:https://codex.wordpress.org/Template_Tags/get_posts

$output1 = '';
$output2 = '';
$args = array('cat'=> 6);
$allposts = get_posts( $args );
foreach ( $allposts as $post ) :
  setup_postdata( $post );
  // Store the titles in one variable
  $output1 .= '<h3>'.get_the_title().'</h3>';
  // And the content in another
  $output2 .= wpautop(get_the_content());
endforeach;
wp_reset_query();

然后在你需要的地方回显 $output1 和 $output2 - 如果你想要更多的控制,你甚至可以将它们存储为数组。您可以将参数添加到 $args 数组以根据需要更改顺序等。

【讨论】:

  • 谢谢!这很有帮助!
  • 很高兴它有帮助 - 如果您需要任何进一步的帮助,请告诉我。学习 get_posts 函数将对您的 WordPress 开发有很大帮助。 WordPress 法典是你的朋友 :)
【解决方案2】:

不好,同样的代码运行两次,你可以在一个循环中使用get_the_title()、get_post()、get_the_content(),它们返回字符串而不是立即输出字符串。

【讨论】:

  • 谢谢!问题是,在一个循环中,我按此顺序得到结果 - 标题、内容、标题、内容,我需要标题、标题、内容、内容。我需要列出,一个列出标题,另一个列出内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
相关资源
最近更新 更多