WordPress.org

Ready to get started?Download WordPress

Forums

Display last featured image from a category (5 posts)

  1. Bloke
    Member
    Posted 2 years ago #

    I have a site that I want to display the last featured image from a category. So I am trying to locate the code to edit that part of the loop. The URL shows it to be in mywebsite/?cat=5 so I would need to edit to display the most recent image from cat 5 LIMIT 1.

  2. blogjunkie
    Member
    Posted 2 years ago #

    You need this code:

    // The Query
    $the_query = new WP_Query( 'cat=5' );
    
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
    	if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
    		the_post_thumbnail();
    	}
    endwhile;
    
    // Reset Post Data
    wp_reset_postdata();
    

    References:

    http://codex.wordpress.org/Class_Reference/WP_Query
    http://codex.wordpress.org/Function_Reference/the_post_thumbnail

  3. Bloke
    Member
    Posted 2 years ago #

    blogjunkie,Thanks for such a quick reply. Where would I put this? I was thinking of just putting it in a margin using a blank text widget.

  4. blogjunkie
    Member
    Posted 2 years ago #

    You need a widget that can execute PHP code. Try searching for it in the plugin directory. Or, put the code directly into your sidebar template file. Good luck

  5. Bloke
    Member
    Posted 2 years ago #

    Ok I got it to work. At first it displayed all records. Now i got:

    $the_query = new WP_Query( 'cat=5&posts_per_page=1' );

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.