2013-07-15 108 views
0

我希望有人可以帮助我解决这个问题。我想添加一个自定义帖子类型(证词)到我的WordPress循环,并显示一个每几个职位。我使用pre_get_posts动作将自定义帖子类型添加到循环中,并且它们显示在循环中,但是我想通过帖子分散这种帖子类型,而不是将它们放在一起。有没有办法做到这一点?任何帮助,将不胜感激。添加自定义帖子类型每个几个帖子

回答

1

如果我正确地阅读它,你会得到一个查询,它既获得了常规的帖子,也获得了自定义的帖子类型的褒奖。所以从理论上讲,你可以根据你的搜索条件抽出10个结果,所有这些结果都是帖子或者所有这些结果将是推荐。

你可能想要做的是做两个查询,一个用于文章,一个用于推荐。这会给你两个post对象的数组,然后很容易循环显示一个类型或另一个类型,这取决于递增的计数器。

大致来说,是这样的:

$args = array('post_type'=>'post', 'posts_per_page'=>9, 'category_name'=>'news); 
$posts = get_posts($args); 

$args = array('post_type'=>'testimonials', 'posts_per_page'=>3); 
$testimonials = get_posts($args); 

/** see how many of the regular posts you got back */ 
$post_count = count($posts); 
/** see how many testimonials you got back */ 
$testimonial_count = count($testimonials); 
/** add them up to get the total result count */ 
$total_count = $post_count + $testimonial_count; 

/** Loop through the total number of results */ 
for($i = 1; $i <= $total_count; $i++){ 

/** assuming you want to show one testimonial every third post */ 
if($i % 3 == 0){ 
    /** this means you're on the a third post, show a testimonial */ 
    setup_postdata($testimonials[$i]); 
} 
else{ 
    /** show a regular post */ 
    setup_postdata($posts[$i]); 
} 

/** and now handle the output */ 
?><h1><?php the_title();?></h1><?php 

} 

在这个例子中它拉一共有12个职位 - 9个员额和3个推荐 - 然后显示一个见证每一个后第三。假设你实际上每个人都有正确的人数。如果您只收到两封推荐信,您会得到一个错误信息,因此您需要在三元运营商之后使用一些代码完成该生产网站,以确保有匹配的证明,并且如果不显示常规帖子等,但应该让你朝着正确的方向前进。

+0

你好,谢谢你的回答。我试图实现这个没有运气。我只有一个帖子重复了11次。 –

相关问题