WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Help: Set Featured Image (4 posts)

  1. Beer
    Member
    Posted 3 years ago #

    I'm using the code below in my theme:
    <?php if ( has_post_thumbnail() ) { the_post_thumbnail('homepage-thumb'); } ?>

    The issue is I've just made this theme update, but it only works if in the post itself it has a featured image set. I'd like to show a 'homepage-thumb' from the post, even if the featured image hasn't explicitly been set.

  2. Rev. Voodoo
    Volunteer Moderator
    Posted 3 years ago #

    http://justintadlock.com/archives/2009/11/16/everything-you-need-to-know-about-wordpress-2-9s-post-image-feature

    Toward the bottom of that writeup is a plugin for displaying other images as featured image

  3. Beer
    Member
    Posted 3 years ago #

    thanks Rev. I've modified my code to this so far....

    <?php
    if ( has_post_thumbnail() ) {
    	the_post_thumbnail('homepage-thumb');
    } else {
    	// get the ID for an attachment for this post
    	$thumb = $wpdb->get_row("SELECT ID, post_title
    		FROM {$wpdb->posts}
    		WHERE post_parent = {$post->ID}
    		AND post_mime_type LIKE 'image%'
    		ORDER BY menu_order LIMIT 1");
    
    	if (! empty($thumb)) {
    		echo wp_get_attachment_image($thumb->ID, 'homepage-thumb');
    	}
    }
    ?>
  4. Beer
    Member
    Posted 3 years ago #

    After reading the codex, this might be better.

    if ( has_post_thumbnail() ) {
    	the_post_thumbnail('homepage-thumb');
    } else {
    	$args = array( 'post_type' => 'attachment', 'post_parent' => $post->ID, 'order_by' => 'menu_order', 'order' => 'ASC' );
    	$attachments = get_posts($args);
    	if ($attachments) {
    		// display just the first attachment result
    		echo wp_get_attachment_image($attachments[0]->ID, 'homepage-thumb');
    	}
    }

Topic Closed

This topic has been closed to new replies.

About this Topic