Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Wordpress, how do I display a single random post of a custom post type in a sidebar widget?

I have created a custom post type - Testimonials - for a WP site I am working on. I want to display a single random testimonial in my sidebar - without using a plugin if possible. Do I need to create a text widget with the proper post query? If so, what would it look like?

Many thanks,

Cynthia

like image 637
Cynthia Avatar asked Jul 22 '12 14:07

Cynthia


People also ask

How do I display a single custom post type in WordPress?

You will need to copy the following code snippet into the template where you wish to display the custom post type. $args = array ( 'post_type' => 'movies' , 'posts_per_page' => 10 ); $the_query = new WP_Query( $args );

How do I show random posts in WordPress?

Display Random Posts in Sidebar Once installed, the Advanced Random Posts Widget plugin adds a widget to your WordPress dashboard. After clicking on Appearance > Widgets, you'll see a widget labeled “Random Posts.” Drag and drop it into your sidebar. In your sidebar, you can click on the widget to expand its settings.


1 Answers

If you want you can directly paste following code snippet in your sidebar.php where you want to show the Testimonials (make sure whether it's testimonials/Testimonials)

<?php
  $args = array(
    'post_type'=>'testimonials', 
    'orderby'=>'rand', 
    'posts_per_page'=>'1'
  );

  $testimonials=new WP_Query($args);

  while ($testimonials->have_posts()) : $testimonials->the_post(); 
?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <p><?php the_excerpt(); // or the_content(); ?></p>
<?php 
  endwhile;
  wp_reset_postdata();
?>
like image 161
The Alpha Avatar answered Sep 18 '22 20:09

The Alpha