WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get random post from specific category (2 posts)

  1. MaddTechWF
    Member
    Posted 4 years ago #

    I have a specific category, lets call it 'testimonials'. I came across this link. After reading it, I'm still a little confused.

    I want to pull a random post from 'testimonials' and display an excerpt of it. I would also like to show a Custom Fields from the post that has the individuals name and lets call it 'WritersName'. How to do I reference it?

  2. MichaelH
    Member
    Posted 4 years ago #

    Assuming testimonials is category 14

    <?php
    //get one random post from category 14, display post title, and excerpt.
    //display WritersName custom field if it exists.
    $args=array(
      'cat' => 14,
      'orderby' => rand,
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of Posts';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
        the_excerpt();
        $name = get_post_meta($my_query->post->ID, 'WritersName', true);
        if ($name){
          echo 'Writers name: ' .$name;
        }
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.