Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Show Random Post from Custom Post Type Taxonomy WordPress

I have a custom post type called 'pc-testimonial' with a custom taxonomy called 'testimonial-categories'.

I'm trying to run a query in the sidebar and randomly show one testimonial at a time based on a testimonial-category'. There are several testimonials per category but for some reason every time I refresh the page the same testimonial keeps showing up. What I'm trying to do is have the testimonial change on every page refresh.

Here's the code for my loop:

<section id="testimonials" class="clr">

<?php
global $post;
$cat = get_post_meta( $post->ID, 'test-cat', true );

$args = array (
'post_type' => 'pc-testimonial',
'orderby' => 'rand',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'testimonial-categories',
'field' => 'slug',
'terms' => $cat
)
)
);
$query = new WP_Query( $args );
?>

<?php while ($query->have_posts()) : $query->the_post(); ?>

<?php the_content(); ?>

<cite><?php the_title(); ?></cite>

<?php endwhile; wp_reset_postdata(); ?>

</section><!-- testimonials -->


Thanks for the help.

Answers (1)

2012-09-17

Rashad Aliyev answers:

For example use it like this.

global $post;

$args = array(

'post_type'=>'ads',
'showposts'=>'1',
'orderby'=>'rand',
'tax_query'=> array( array(
'taxonomy' => 'rotation',
'field' => 'slug',
'terms' => $position,
'operator' => 'IN',
), ),
);

$my_query = new WP_Query($args);
while ($my_query->have_posts()) : $my_query->the_post();
// Display post details here. Example: the_title(), the_permalink(), etc.
endwhile;

}


P.S: Don't forget to apply here your custom post type and taxonomy


Denis Leblanc comments:

That's exactly what I'm using except that I'm using 'posts_per_page' instead of the deprecated 'showposts' parameter.

I'm able to get testimonials showing, they're just not rotating on every page refresh.


Rashad Aliyev comments:

Please try my code. That'll worked!


Denis Leblanc comments:

I did.


Rashad Aliyev comments:

I hope you've got many data. Because of it's getting random. If you have a few data then put the a few times on refresh button. It should be display rotation.