0

I have a feeling that I'm on the right track, I just don't have enough solid PHP knowledge to get much further than where I'm currently at.

I'm currently using the following code to return a list of child categories from a single category:

<?php
    $taxonomyName = "category";
    $terms = get_terms($taxonomyName,array('parent' => 79));
    echo '<ul>';
    foreach($terms as $term) {
        echo '<li>';
        echo '<a href="'.get_term_link($term->slug,$taxonomyName).'">'.$term->name.'</a><br/>';

        $thumbnails = get_posts('numberposts=1&orderby=rand');
        foreach ($thumbnails as $thumbnail) {
        echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
            if ( has_post_thumbnail($thumbnail->ID)) {
                echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail');
            } else {
            echo 'no thumbnail';    
        }
        echo '</a>';
        }
        echo '<li>';
    }
    echo '</ul>';
?>

This code works somewhat. It returns a list of all six sub categories under the parent, ID 79. However, I want to also return one random thumbnail in each of the list items for each of the 6 sub categories.

Unfortunately, this code returns a random thumbnail from all of my posts, not just ID 79 and it's specific child. I need it to return one thumbnail from the same category that is returned in it's parent <li>.

Is there some easy way to do this? I'm thinking I need to sort through that array and return the category in the nested foreach loop. I just don't know how to do that.

Thanks in advance for any help!

1

So in order to do this, I needed to first do a for each loop, store the category slug as a variable, JAMterm, and then use that in a query to pull one random thumbnail from the category.

Thanks to @Renishkhunt for helping me along the way to get this answer.

<?php
    $taxonomyName = "category";
    $terms = get_terms($taxonomyName,array('parent' => 79));
    echo '<ul>';
    foreach($terms as $term) {
        echo '<li><a href="'.get_term_link($term->slug,$taxonomyName).'">'.$term->name.'</a><br/>';

        $JAMterm = $term->slug;

        global $wp_query;
        $term = $wp_query->queried_object;

        $args=array(
            'orderby' => 'rand',
            'posts_per_page' => 1,
            'post_type' => 'post',
            'tax_query' => array(
                array(
                    'taxonomy' => 'category', 
                    'field' => 'slug', 
                    'terms' =>  $JAMterm
                )
            )
        );

        $new_query = null;
        $new_query = new WP_Query($args);

        while ($new_query->have_posts()) : $new_query->the_post();
            the_post_thumbnail(); 
        endwhile;
        wp_reset_postdata();


        echo '</li>';
        }
    echo '</ul>';
?>
0

you also used to display random sub category using shuffle function.

<?php
$term_id = 97;
$taxonomy_name = 'category';
$terms = get_term_children( $term_id, $taxonomy_name );

echo '<ul>';
shuffle($terms);
for($i = 0 ;$i < 1; $i++ ){
    echo '<li>';
    echo '<a href="'.get_term_link($terms[$i]->slug,$taxonomyName).'">'.$terms[$i]->name.'</a><br/>';
        $thumbnails = get_posts('numberposts=1&orderby=rand');
         foreach ($thumbnails as $thumbnail) {
            if ( has_post_thumbnail($thumbnail->ID)) {
                   echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail');
            } else {
                   echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
                   echo 'no thumbnail';    
                   echo '</a>';
            }
          }
   echo "</li>";       
}

echo '</ul>';
?> 

i hope this code is used full for you.

this is return random sub category.

thank you.

  • Thanks for the quick reply. Unfortunately, I'm getting an error: Catchable fatal error: "Object of class WP_Error could not be converted to string" - Any ideas? – Jeremy Miller Nov 12 '13 at 5:07
  • I managed to get rid of the error by changing the first two lines in your code to: $taxonomyName = "category"; $terms = get_terms($taxonomyName,array('parent' => 79));, unfortunately the thumbnails it is returning are doing the same as in my code. It also seems to be returning only one category, not all 6 that are there. It doesn't seem to work. – Jeremy Miller Nov 12 '13 at 5:11
  • Upon further inspection it looks like the code concerning the thumbnail was the same code that I provided which was not working properly. The part concerning the list of categories was fine and working as I needed. It was only the thumbnail part that is not working. Thanks for your help anyway though, I appreciate it. – Jeremy Miller Nov 12 '13 at 5:17
  • 1
    @JeremyMiller used WP_Query instead of get_posts.stackoverflow.com/questions/10918814/… please check this and used if you help full. – Renish Khunt Nov 12 '13 at 6:06
  • Thanks for the follow up, but that doesn't do what I need it to do. I need it to return all of my categories but pull one random thumbnail from each category. This code you linked to seems to randomize all posts, not pull one image from each category. – Jeremy Miller Nov 13 '13 at 3:21
0

Since all you want is random thumbnail and not all the posts data, you could use a direct query like this (# please set your real table names or use $wpdb->prefix):

SELECT 
    m.meta_value
FROM 
    wp_posts p 
    INNER JOIN wp_postmeta m ON m.post_id = p.ID
    INNER JOIN wp_term_relationships rel ON p.ID = rel.object_id
    INNER JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
    INNER JOIN wp_terms t ON tt.term_id = t.term_id
WHERE 
    p.post_type = 'your post type'  # please set as needed 
    AND p.post_status = 'publish'
    AND m.meta_key = '_thumbnail_id'
    AND t.slug in ('your slug list') # please set as needed
    #AND t.term_id in ('yout id list') # alternative: a list of term ids
ORDER BY RAND()
LIMIT 1

You'll get exactly 1 post thumbnail ID from the list of published posts that belong to a specific term of a specific taxonomy or category. Then get your thumbnail data by using wp_get_attachment_image_url() or some of the other attachment-related functions available form WP.

Generally speaking, when there are no native wordpress functions to retrieve your data, I think it's best to spend some time to build a custom query, since it's often faster and you can then embed it on some utility function to use again when needed.

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.