0
votes

I was hoping someone could help me with this problem. I am wanting to add a custom post type(testimony) to my WordPress loop and display one every few posts. I added the custom post type to the loop using the pre_get_posts action and they show up in the loop but I want to scatter just this post type through out the posts and not have them together. Is there a way to do this? Any help would be appreciated.

1

1 Answers

1
votes

If I'm reading it correctly you've got one query that is getting both regular posts and your custom post type testimonials. So theoretically you could pull 10 results all of which would be posts or all of which would be testimonials, depending on your search criteria.

What you probably want to do is make two queries, one for posts and one for testimonials. That will give you two arrays of post objects and then it's easy to loop through and display one type or the other depending on an incremented counter.

Very roughly, something like:

$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

}

In this example it's pulling a total of 12 posts -- 9 posts and 3 testimonials -- and then showing a testimonial every third post. It's assuming you actually have the correct number of each one. If you only got back two testimonials you'd get an error, so one a production site you'd want to finish it off with some code in after the ternary operator to make sure that there is a matching testimonial and if not show a regular post, etc. But should get you going in the right direction.