0

This code below works perfect to pull the title of five random categories, the issue is for each random category I want the latest post title and thumbnail but where and how do I add the post query?

<?php
//display random sorted list of terms in a given taxonomy
$counter = 0;
$max = 5; //number of categories to display
$taxonomy = 'category';
$terms = get_terms($taxonomy);
shuffle ($terms);
//echo 'shuffled';
if ($terms) {
foreach($terms as $term) {
    $counter++;
    if ($counter <= $max) {
    echo '<p><a href="' . get_category_link( $term->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
    }
}
}
?>
1

If I'm not wrong a the_post() function will take the post info into the loop. If so, then the the_title() and the_post_thumbnail() will do the rest for you.

<?php
//display random sorted list of terms in a given taxonomy
$counter = 0;
$max = 5; //number of categories to display
$taxonomy = 'category';
$terms = get_terms($taxonomy);
shuffle ($terms);

the_post();
if ($terms) {
foreach($terms as $term)
    {
        $counter++;
        if ($counter <= $max)
        {
            echo '<p><a href="' . get_category_link( $term->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
            echo '<p><a href="' . the_permalink() . '">' . the_title() . '</a></p>';
            echo '<p><a href="' . the_permalink() . '">' . the_post_thumbnail( 'thumbnail' ) . '</a></p>';
        } //endif ($counter <= $max)
    }
} //endif ($terms)
?>

NOTE: I haven't tested it. Please let me know whether it works or not.

6
  • 1
    Almost there, the output is the url not the thumbnail or title thanks for helpnig really need this. – Jaz Sep 19 '13 at 1:21
  • ok the url is the permalink – Jaz Sep 19 '13 at 1:35
  • the title only works but not the thumbnail, the permalink is not linking it writes out. – Jaz Sep 19 '13 at 1:43
  • If your images are from post_thumbnail (commonly known as: Featured Image) then it'll be viewed. If it's not, then won't. – Mayeenul Islam Sep 19 '13 at 6:12
  • Is there a way to get? the_post_thumbnail() is not working – Jaz Sep 19 '13 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.