Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Fallback Image for Dynamic Image from Post Meta

  • I have an image block that displays an image based on a custom field testimonial_photo. If no testimonial photo exists, I’d like the block to automatically display the featured image instead. Is this possible? Thanks.

    — Aaron

  • 1. Add this PHP code to add a fallback image ID to the image:

    add_filter( 'generateblocks_dynamic_image_fallback', 'custom_dynamic_image_fallback', 10, 3 );
    
    function custom_dynamic_image_fallback( $featured_image_id, $attributes, $block ) {
        if ( isset( $attributes['className'] ) && strpos( $attributes['className'], 'my-image' ) !== false ) {
    	$featured_image_id = get_post_thumbnail_id(get_the_ID());
            $image = get_post_meta(get_the_ID(), 'testimonial_photo', true);
            if ( $image ) {
                // return the $image
                return $image;
            }
        }
    
        return $featured_image_id;
    }

    Adding PHP: https://docs.generatepress.com/article/adding-php/

    2. Add my-image class to the image block.
    Adding CSS class(es): https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/

  • That worked like a charm. Thanks.

    — Aaron

  • You are welcome   🙂

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.