Swap Content Blocks with Code?

Hi, All -

Is there a way to swap out content blocks with code? I have a client who is really enjoying their new site but hasn’t grasped the concept of image orinentation! The site looks fabulous when they post a featured image taken in landscape mode - but falls apart when they use a portrait pic.

In an ideal world I want to be able to swap the content block based on the dimensions of the featured image. When it’s in landscape it can appear above the post as normal. When they use a portrait shot, however, I want to use another block which displays the image at the side of the post.

It should be easy to create a conditional based on the image post thumbnail size - but how would I swap the blocks?

Can it be done?

:slight_smile:

Antar

I assume its a GP build - if so it would be easier to create 2 x Elements - one for Portrait and one for Landscape. Then use the generate_element_display filter to set the correct element for display.

Heres an example of the filter being used:

And heres a real rough function for returning the attachments orientation:

function return_featured_image_orientation($landscape) {
    $landscape = '';
    $img = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), "full" );
    $width = $img[1];
    $height = $img[2];
    if ( $width >= $height ) {
      $landscape = true;
    } 
    return $landscape;
}

David -

This is perfect. It’s exactly what I was looking for.

Thanks!

Antar

David -

I’ve come up with the following code. It works but I don’t know if it’s efficient. Also, I believe I need both examples - one each to switch off each block depending on the circumstances. Can it be done with only a single piece of code?

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
    global $post;
	$thumb_id = get_post_thumbnail_id( $post->ID );
    $img = wp_get_attachment_metadata( $thumb_id );
	$width = $img['width'];
	$height = $img['height'];
    $landscape = '';
	if ( $width >= $height ) {
      $landscape = true;
    } 
	
	if ( 16 === $element_id ) { // Only target the portrait block
        if ( $landscape ) {
            $display = false;
        }
    }
   return $display;
}, 10, 2 );

and

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
    global $post;
	$thumb_id = get_post_thumbnail_id( $post->ID );
    $img = wp_get_attachment_metadata( $thumb_id );
	$width = $img['width'];
	$height = $img['height'];
    $landscape = '';
	if ( $width >= $height ) {
      $landscape = true;
    } 
	
	if ( 15 === $element_id ) { // Only target landscape block
        if ( !$landscape ) {
            $display = false;
        }
    }
   return $display;
}, 10, 2 );

Any good?

Thanks again!

:slight_smile:

Antar

Looks good to me - aside of using a helper function which for two elements is not really worth it - thats as good as it gets - and you can’t combine the filters