Automatically set the featured image

Method 1: Using the publish_post hook* and media_sideload_image()

Here we will upload an image from a URL, attach it to the post, and set it as the featured image when the post is published.

*Actually, we’re using the dynamic hook {$new_status}_{$post->post_type}, which refers transitioning a post post type to the publish status. See wp-includes/post.php for details.

This example code applies when publishing the post type post. A check is in place so that we do not automatically assign the featured image if one has been manually set. Feel free to customize this as desired.

/**
 * Download image, attach it to the current post, and assign it as featured image
 * upon publishing the post.
 *
 * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
 * refer to the new post status and post type, respectively.
 *
 * Please note: When this action is hooked using a particular post status (like
 * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
 * first transitioned to that status from something else, as well as upon
 * subsequent post updates (old and new status are both the same).
 *
 * @param int     $post_id Post ID.
 * @param WP_Post $post    Post object.
 */
add_action( 'publish_post', 'wpse_default_featured_image', 10, 2 );
function wpse_default_featured_image( $post_id, $post ) {
    // Bail if there is already a post thumbnail set.
    $current_post_thumbnail = get_post_thumbnail_id( $post_id );
    if ( '' !== $current_post_thumbnail ) {
        return;
    }

    $url="https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg";
    $title = "The default featured image.";

    $image = media_sideload_image( $url, $post_id, $title, 'id' );
    set_post_thumbnail( $post_id, $image );
}

Method 2: Applying a filter to the post thumbnail.

By using a filter, we can “virtually” set the post thumbnail. This method makes it easier to change the post thumbnail on the fly for all posts.

Filter 1: post_thumbnail_html

The post_thumbnail_html filter can be used to override the HTML output for the post thumbnail:

/**
 * Filters the post thumbnail HTML.
 *
 * @param string       $html              The post thumbnail HTML.
 * @param int          $post_id           The post ID.
 * @param string       $post_thumbnail_id The post thumbnail ID.
 * @param string|array $size              The post thumbnail size. Image size or array of width and height
 *                                        values (in that order). Default 'post-thumbnail'.
 * @param string       $attr              Query string of attributes.
 */
add_filter( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 );
function wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
    return '<img src="https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg" alt="Have a cigar">';
}

Filter 2: Using get_post_metadata on the _thumbnail_id meta key.

Here’s another approach that overrides each post’s thumbnail ID with a different ID.

I’d suggest implementing a Customizer setting or options page that allows the special thumbnail image to be uploaded/selected (locally, from a URL, or from the medial library). Then you can use the get_post_metadata filter to modify the value associated with each post thumbnail’s meta key _thumbnail_id:

/**
 * Dynamic hook: "get_{$meta_type}_metadata"
 * 
 * Filters whether to retrieve metadata of a specific type.
 * 
 * The dynamic portion of the hook, `$meta_type`, refers to the meta
 * object type (comment, post, or user). Returning a non-null value
 * will effectively short-circuit the function.
 *
 * @param null|array|string $value     The value get_metadata() should return - a single metadata value,
 *                                     or an array of values.
 * @param int               $object_id Object ID.
 * @param string            $meta_key  Meta key.
 * @param bool              $single    Whether to return only the first value of the specified $meta_key.
 */
add_filter( 'get_post_metadata', 'wpse_featured_image_id_override', 100, 4 );
function wpse_featured_image_id_override( $value, $object_id, $meta_key, $single ) {
    $thumbnail_id_key = '_thumbnail_id';

    // Bail if this is not the correct meta key. Return the original value  immediately.
    if ( ! isset( $meta_key ) || $thumbnail_id_key !== $meta_key ) {
        return $value;
    }

    // Add additional guard clauses if necessary... (check post type, etc.)

    // Get the id for an image uploaded elsewhere.
    // This could be pulled from the customizer or a plugin options page.
    return 807;  // Example ID
}

Leave a Comment