Enjoying these plugins? ☕ Buy me a coffee to support ongoing development.

Featured Image from First Image

A WordPress plugin that automatically sets the first image in post content as the featured image if none is set. Works with both local and remote images.

Single File v1.0.0 Updated 1 month ago

YT Featured Image from First Image

A WordPress plugin that automatically sets the first image in post content as the featured image if none is set. Works with both local and remote images.

Features

  • Automatic Featured Image: Automatically detects and sets the first <img> tag in content as featured image
  • Remote Image Support: Downloads and imports external images to your media library
  • Per-Post Control: Disable auto-featured image on individual posts via meta box
  • Post Type Selection: Choose which post types should have auto-featured images
  • Smart Detection: Only sets featured image if none exists (unless overwrite is enabled)
  • Safe Operation: Runs on save_post hook with proper validation
  • WPCS Compliant: Follows WordPress coding standards with proper sanitization and escaping

Installation

  1. Upload the yt-featured-image-from-first-image folder to the /wp-content/plugins/ directory
  2. Activate the plugin through the 'Plugins' menu in WordPress
  3. Configure settings at Settings → Featured Image
  4. The plugin will automatically work when you save posts

How It Works

When you save a post:

  1. Check if enabled: Plugin verifies it's enabled globally and for this post type
  2. Check for existing featured image: If one exists and overwrite is disabled, skip
  3. Check per-post setting: If disabled via meta box, skip
  4. Extract first image: Scans content for the first <img> tag
  5. Find or download image:
    • If image is local (in media library), use its attachment ID
    • If image is remote and remote images are allowed, download it
  6. Set featured image: Assigns the image as the post's featured image

Settings

Navigate to Settings → Featured Image to configure:

Main Settings

  • Enable Auto-Featured Image: Toggle the plugin functionality on/off
  • Post Types: Select which post types should have auto-featured images
  • Remote Images: Allow downloading and importing external images
  • Overwrite Existing: Replace existing featured images (use with caution)

Default Settings

  • Enable Auto-Featured Image: ✓ Enabled
  • Post Types: Posts and Pages
  • Remote Images: ✓ Enabled
  • Overwrite Existing: ✗ Disabled

Per-Post Control

On the post edit screen, you'll find an "Auto Featured Image" meta box in the sidebar:

  • Checkbox: "Disable auto-featured image for this post"
  • Check this to prevent the plugin from setting a featured image on a specific post
  • Useful for posts where you want manual control or no featured image

Usage Examples

Basic Usage

  1. Create a new post
  2. Add content with an image:
    <p>Some text here...</p>
    <img src="https://example.com/image.jpg" alt="My Image">
    <p>More content...</p>
  3. Save the post
  4. The first image is automatically set as the featured image

With Local Images

If you insert images from your WordPress media library:

<img src="https://yoursite.com/wp-content/uploads/2024/01/photo.jpg" alt="Photo">

The plugin finds the attachment ID and sets it as the featured image instantly.

With Remote Images

If you paste external image URLs:

<img src="https://external-site.com/images/photo.jpg" alt="External Photo">

The plugin (if remote images are enabled):

  1. Downloads the image
  2. Imports it to your media library
  3. Sets it as the featured image

Disable for Specific Post

  1. Edit the post
  2. Find the "Auto Featured Image" meta box in the sidebar
  3. Check "Disable auto-featured image for this post"
  4. Save the post
  5. Plugin will skip this post

File Structure

yt-featured-image-from-first-image/
├── class-yt-featured-image-from-first-image.php  # Main plugin file (~590 lines)
├── assets/
│   ├── css/
│   │   └── yt-featured-image-ffi-admin.css       # Admin styles
│   └── js/
│       └── yt-featured-image-ffi-admin.js        # Admin interactions
└── README.md                                      # This file

Prefix Convention

All functions, classes, and elements use the yt_featured_image_ffi prefix:

  • Class: YT_Featured_Image_From_First_Image
  • Constants: YT_FEATURED_IMAGE_FFI_*
  • Functions: yt_featured_image_ffi_*
  • Post Meta: _yt_featured_image_ffi_disable
  • Options: yt_featured_image_ffi_options
  • Text Domain: yt-featured-image-from-first-image

How Images Are Detected

Local Images

The plugin identifies local images by:

  1. Checking the guid field in the posts table (exact URL match)
  2. Checking the _wp_attached_file meta key (relative path match)

Remote Images

Remote images are:

  1. Detected if the URL doesn't match local upload directory
  2. Downloaded using download_url()
  3. Imported using media_handle_sideload()
  4. Attached to the post automatically

Security Features

  • Capability checks (edit_post, manage_options)
  • Nonce verification for meta box saves
  • Input sanitization (sanitize_text_field, esc_url_raw)
  • Output escaping (esc_html, esc_url, esc_attr)
  • Autosave and revision detection
  • Safe file download and validation

Performance Considerations

  • Only runs on save: Doesn't affect front-end performance
  • Smart detection: Skips processing if not needed
  • Caches lookups: Uses database queries efficiently
  • Error handling: Fails gracefully if image download fails

Hooks Integration

Actions Used

  • save_post (priority 20): Main functionality
  • save_post (priority 10): Meta box save
  • add_meta_boxes: Register meta box
  • admin_enqueue_scripts: Load admin assets

Available Filters

While this plugin doesn't expose custom filters, you can use WordPress core filters:

// Prevent plugin from running on specific conditions
add_filter('save_post', function($post_id, $post) {
    if (your_condition) {
        remove_action('save_post', array($plugin_instance, 'yt_featured_image_ffi_auto_set_featured_image'), 20);
    }
}, 5, 2);

Troubleshooting

Featured image not being set?

Check:

  1. Plugin is activated
  2. "Enable Auto-Featured Image" is checked in settings
  3. Post type is selected in settings
  4. Post has at least one image in content
  5. "Disable auto-featured image" is NOT checked in the post meta box
  6. No existing featured image (unless overwrite is enabled)

Remote images not downloading?

Ensure:

  1. "Remote Images" is enabled in settings
  2. Your server can make external HTTP requests
  3. The remote server allows downloads (no 403/404 errors)
  4. File permissions allow uploads to media library

Plugin affecting performance?

  • The plugin only runs on save_post, not on front-end
  • If concerned about remote downloads, disable "Remote Images"
  • Consider disabling "Overwrite Existing" to prevent unnecessary processing

Uninstallation

When the plugin is deleted via WordPress admin:

  1. All plugin options are removed
  2. Post meta (_yt_featured_image_ffi_disable) is deleted
  3. WordPress cache is flushed
  4. Featured images that were set remain (they're part of your content)

Requirements

  • WordPress 5.8 or higher
  • PHP 7.4 or higher
  • allow_url_fopen enabled (for remote image downloads)
  • Write permissions for wp-content/uploads

Complexity

  • Main PHP File: ~590 lines (with comments)
  • CSS File: ~45 lines
  • JS File: ~110 lines
  • Total: ~745 lines across all files

FAQ

Does this work with page builders?

It depends on how the page builder stores content. If images are in the post content (not as metadata), the plugin should detect them.

What if I have multiple images?

Only the first image in the content is used.

Can I change which image is used?

Not automatically. The plugin always uses the first <img> tag. To use a different image, either:

  • Reorder your images in the content
  • Disable auto-featured image and set manually

Does it work with image blocks (Gutenberg)?

Yes! Gutenberg blocks are rendered to HTML with <img> tags, which the plugin can detect.

Will it replace my manually set featured images?

Only if you enable "Overwrite Existing" in settings. By default, it respects existing featured images.

Does it work with images in galleries?

Yes, if the gallery shortcode or block renders <img> tags in the post content.

What about images in custom fields?

No, the plugin only scans the main post content (post_content).

Best Practices

  1. Start with defaults: Enable the plugin with default settings first
  2. Test on staging: Try it on a test post before bulk operations
  3. Don't enable overwrite: Unless you have a specific need, leave it disabled
  4. Use per-post disable: For posts with specific needs, use the meta box
  5. Monitor remote downloads: Check if external images are actually needed

Changelog

1.0.0

  • Initial release
  • Automatic featured image from first image in content
  • Remote image download and import
  • Per-post disable option via meta box
  • Post type selection
  • Overwrite existing option
  • Admin UI with settings page

License

GPL v2 or later

Author

Krasen Slavov

Support

For issues and feature requests, please visit the GitHub repository.