【问题标题】:Wordpress loop inside loopWordpress 循环内循环
【发布时间】:2014-12-12 15:33:33
【问题描述】:

我有一个正常的循环,根据给定的 $args 输出帖子。 在三个帖子之后,我想插入一个来自精选类别的帖子。我试过以不同的组合开始一个新的 WP_Query,简单的 query_posts。似乎没有任何效果。任何想法为什么?

$args = array(
    'post_type' => 'post', 
    'posts_per_page' => $count,
    'paged' => $paged,
    'page' => $paged,
    'cat' => $cat,
    'ignore_sticky_posts' => 1
);

// create a new instance of WP_Query
$my_query = new WP_Query($args);

<ul>
<?php 
$i = 0;
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); 

 if($i == 3): ?>
    <li> //insert here one post from featured category
    </li>
<?php endif; ?>

<li>
// the normal query stuff is here
</li>
<?php $i++ //post counter
endwhile; //end loop while
endif; //end loop 
?>
</ul>

【问题讨论】:

  • 所以任何其他方式在循环中获取帖子,期望使用 get_post() 可以工作但需要确切的 id ?
  • 当您执行 the_post() 时,您应该能够访问和设置来自 $post 变量的任何内容。因此,首先运行您的功能查询并将该特色项目的内容设置在其自己的变量中,例如$featured = $post - 然后在您的条件$i == 3 中您可以说$feature-&gt;post_titleget_permalink($feature-&gt;ID) 等。您不必运行另一个循环内的循环。

标签: php wordpress


【解决方案1】:

我是这样做的。在主要查询之前,我对特色帖子进行了特殊查询。

$args2 = array(
        'post_type' => 'post', 
        'posts_per_page' => 1,
        'category_name' => 'TheCategoryName-Slug',
        'ignore_sticky_posts' => 1
);

$my_query2 = new WP_Query($args2);
$post_ids = array(); //create an array to store the ids of the posts
if ($my_query2->have_posts()) : while ($my_query2->have_posts()) : $my_query2->the_post();
  $post_ids[] = get_the_ID();
 endwhile;
 wp_reset_postdata();
endif;

获得所有 ID 后,您可以使用它们来获取所需的数据。基本上,来自 wp_posts 表 (http://codex.wordpress.org/Database_Description#Table:_wp_posts) 的所有数据。帖子作者作为 id 返回,可用于使用 get_userdata() 函数获取名称。

echo get_post_field('post_title', $post_ids[0]);
echo get_post_field('post_author', $post_ids[0]);
echo get_post_field('post_date', $post_ids[0]);

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2012-12-22
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多