• Resolved zenitg9

    (@zenitg9)


    Hi, I’m trying to set the last image of any post as featured, actually I have found a php function but it takes the first image of the media library not from my post. I am not a coder, could someone please help me to edit the function so that i can accomplish this?

    function auto_set_featured() {
    global $post;
    $has_thumb = has_post_thumbnail($post->ID);
    if (!$has_thumb)  {
    $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID, $attachment_id);
            }
        }
    }
    }
    add_action('the_post', 'auto_set_featured');
    add_action('save_post', 'auto_set_featured');
    add_action('draft_to_publish', 'auto_set_featured');
    add_action('new_to_publish', 'auto_set_featured');
    add_action('pending_to_publish', 'auto_set_featured');
    add_action('future_to_publish', 'auto_set_featured');

    Thanks for your time

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi @zenitg9
    Although there may be much better way to do this.
    but you try this code.

    
    function auto_set_featured() {
    	global $post;
    	$has_thumb = has_post_thumbnail($post->ID);
    	if (!$has_thumb)  {
    		$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
    		if ($attached_image) {
    			$thumb_flag = 0;
    			foreach ($attached_image as $attachment_id => $attachment) {
    				$attachment_array_size =  sizeof($attached_image);
    				// If it is last thumb image of attachment array.
    				if( $attachment_array_size == ( $thumb_flag +1) ){
    					set_post_thumbnail($post->ID, $attachment_id);
    				}
    				$thumb_flag++;
    			}
    		}
    	}
    }
    add_action('the_post', 'auto_set_featured');
    add_action('save_post', 'auto_set_featured');
    add_action('draft_to_publish', 'auto_set_featured');
    add_action('new_to_publish', 'auto_set_featured');
    add_action('pending_to_publish', 'auto_set_featured');
    add_action('future_to_publish', 'auto_set_featured');
    
    • This reply was modified 7 years, 9 months ago by 1naveengiri.
    Thread Starter zenitg9

    (@zenitg9)

    Thank you so much 1naveengiri, it works like a charm!, I’m sure this will help other people not only me.

    I really appreciate it!

    • This reply was modified 7 years, 9 months ago by zenitg9.

    your welcome @zenitg9 ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to set the last WordPress post image as a featured image?’ is closed to new replies.