Skip to content

Define a Fallback for the Image Element

The following snippet will show you how to set a fallback image ID for the Image Element when it's set to display a featured image. Now, if you want to actually display a fallback for ANY featured image on your site (elements, widgets, cards, etc) you may want to instead use the following snippet.

/**
 * Set fallback for the Image element when set to display the featured image.
 *
 * @link https://totalwptheme.com/docs/snippets/featured-image-element-fallback/
 */
add_action( 'shortcode_atts_vcex_image', function( $atts ) {
    if ( ! isset( $atts['source'] ) || 'featured' !== $atts['source'] || has_post_thumbnail() ) {
        return $atts; // don't target this element
    }

    // Option 1: Define a fallback from the media library based on it's ID.
    $atts['source'] = 'media_library';
    $atts['image_id'] = '42';

    // Option 2: Define a fallback from a URL
    $atts['source'] = 'external';
    $atts['external_image'] = 'URL';

    // Return shortcode attributes
    return $atts;
}, 10 );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Related Snippets
Back To Top