WordPress function to set a default featured image if none has been set

You can use the following WordPress function to set a default featured image if none has been set. This function checks if the current post has a featured image. If not, it sets the provided image URL as the default featured image.

Add this code to your theme’s functions.php file:

function set_default_featured_image($post_id) {
    // Check if the post already has a featured image
    if (!has_post_thumbnail($post_id)) {
        // Image ID from the URL
        $default_image_id = attachment_url_to_postid('https://eplreport.com/wp-content/uploads/2024/08/default.webp');
        
        // Set the default featured image
        if ($default_image_id) {
            set_post_thumbnail($post_id, $default_image_id);
        }
    }
}
add_action('save_post', 'set_default_featured_image');

Explanation:

  • attachment_url_to_postid: Converts the image URL to the corresponding attachment ID.
  • set_post_thumbnail: Sets the featured image using the attachment ID.

This version directly uses the existing image that is already uploaded, making it straightforward and efficient. This function will automatically set the default featured image for posts that do not have one when they are saved.