I have a custom post type called "Testimonials." I also have a custom taxonomy called "Products," where each term is a different product, like "Product A", "Product B", etc. This way, I can attach a testimonial to a specific product.
I'm trying to list all my testimonials on one page, but grouped by product. ("Testimonials for Product A," etc.)
I have a piece of code that works well for categories, so I changed it to taxonomies. Nothing comes out or it repeats the same posts over and over again. As you can imagine, it doesn't work. Where am I going wrong?
<?php
wp_reset_query();
$taxonomies = get_taxonomies('');
foreach ( $taxonomies as $taxonomy ) :
$args = array(
'posts_per_page' => 5,
'taxonomy' => $taxonomy->term_id,
);
query_posts($args);
if (have_posts()) :
echo '<h2>Latest Testimonials for '.$taxonomy->name.' Product</h2>';
while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php else :
echo '<h2>No Testimonials for '.$taxonomy->name.' Product</h2>';
endif; wp_reset_query; ?>
<?php endforeach; ?>
Ivaylo Draganov answers:
Hello,
maybe try something like this:
[[LINK href="http://pastebin.com/7tPY93pX"]]http://pastebin.com/7tPY93pX[[/LINK]]
Ivaylo Draganov comments:
Oops, I had forgotten to put the <em>echo</em> command(you wouldn't see anything without it). The amended code is at the same URL.
Michel Fortin comments:
Unfortunately, all I get is "No Testimonials for Product" repeated several times. Nothing else. BTW, I have added this to functions, which is why it worked with categories:
add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
if(is_category() || is_tag() || is_taxonomy()) {
$post_type = get_query_var('post_type');
if($post_type)
$post_type = $post_type;
else
$post_type = array('post','testimonials'); // replace cpt to your custom post type
$query->set('post_type',$post_type);
return $query;
}
}
Maybe that's the code that's wrong?
Ivaylo Draganov comments:
The problem might be with the post type and taxonomy name. I've abstracted them to variables at the top of the script now. Please set them correctly and try again (it's the same URL for the code).
Michel Fortin comments:
It works!
John Cotton answers:
Have you tried [[LINK href="http://codex.wordpress.org/Function_Reference/get_objects_in_term"]]get_objects_in_term[[/LINK]] ?
John Cotton comments:
('DESC' in the args will give you the most recent first...)
Romel Apuya answers:
try this.
<?php
wp_reset_query();
$taxonomies = get_taxonomies('');
foreach ( $taxonomies as $taxonomy ) :
$args = array(
'post_type' => 'testimonials',
'post_status' => 'publish',
'order' =>DESC,
'taxonomy' => $taxonomy->term_id,
'posts_per_page' => 5
);
?>