• Hi all,

    Is there a way to automatically add a featured image when publishing a post based on the first image inside the gallery of the post.

    FYI: I am not attaching any images to my posts. I am just using the gallery shortcode [gallery].

    many thanks,
    Maraki

Viewing 8 replies - 1 through 8 (of 8 total)
  • When you use the gallery shortcode you are attaching images to the post. Here is a function that will create the featured image for you when you save the post.

    function wp_support_create_feature( $post ) {
         if ( defined('DOING_AUTOSAVE' && DOING_AUTOSAVE )
            return $post;
    
        if ( has_post_thumbnail( $post ) )
            return $post
    
        $first = get_children( array(
    				'post_parent'    => $post->ID,
    				'post_type'      => 'attachment',
    				'post_mime_type' => 'image',
    				'posts_per_page' => (int)1,
    			), ARRAY_A
    		);
        set_post_thumbnail( $post->ID, $first[0]['ID'] );
    }
    add_action( 'save_post', 'wp_support_create_feature' );
    Thread Starter maraki

    (@neodjandre)

    thanks Chris for your prompt reply, will test this today..

    Will this work if people press the “Publish” button without saving first?

    x

    As much as this is requested, it should be a checkbox in Settings->Media.

    BTW, the above code works great.

    Thread Starter maraki

    (@neodjandre)

    ok, i am getting a syntax error when i try to add the above function, i think some of the brackets are incorrect!

    Thread Starter maraki

    (@neodjandre)

    Parse error: syntax error, unexpected T_RETURN

    and i have to replace manually my functions.php with FTP as this error pertains even when i try to update the functions file

    Try:

    function wp_support_create_feature( $post ) {
         if ( defined('DOING_AUTOSAVE' && DOING_AUTOSAVE )
            return $post;
    
        if ( has_post_thumbnail( $post ) )
            return $post;
    
        $first = get_children( array(
    				'post_parent'    => $post->ID,
    				'post_type'      => 'attachment',
    				'post_mime_type' => 'image',
    				'posts_per_page' => (int)1,
    			), ARRAY_A
    		);
        set_post_thumbnail( $post->ID, $first[0]['ID'] );
    }
    add_action( 'save_post', 'wp_support_create_feature' );

    Inserted missing ; after the second return.

    Thread Starter maraki

    (@neodjandre)

    corrected the errors… function doesn’t work as expected either..

    Thread Starter maraki

    (@neodjandre)

    Test this by:

    1. Creating a post with no images
    2. Adding a couple of images in the gallery of the post
    3. Saving or publishing the post

    The featured image is not set automatically.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Automatic Featured Image’ is closed to new replies.