-
jgsearch
Hi,
I’m trying to add an iframe shortcode dynamically.
I have a Headline block which displays the src URL from an ACF field. To make this a shortcode, I wanted to add the text ‘[iframe src=”‘ before the src URL, and then add ‘” width=”640″ height=”480″]’ after the src URL, making it a complete shortcode. How can I do this using a code snippet in PHP? I tried to search but I don’t know where to start as I’m not very good in PHP. Thanks! -
Hi there,
You may try something like this:
add_filter( 'generateblocks_dynamic_content_output', function($content, $attributes) { $class_name = $attributes['className'] ?? ''; if ('dynamic-shortcode' !== $class_name) { return $content; } // Check if the content is a URL (coming from an ACF field) if (filter_var($content, FILTER_VALIDATE_URL)) { // Create the shortcode $shortcode = sprintf( '[iframe src="%s" width="640" height="480"]', esc_url($content) ); return $shortcode; } return $content; }, 10, 2 );
Then give the dynamic headline block this CSS class in the “Advanced” panel:
dynamic-shortcode
Let me know if that works.
-
jgsearch
Hi Alvind! Thank you for the code but it didn’t work on my end. Could you please check what I did? I’ll send the login in private.
-
My code might not be working because it’s still outputting the URL even everything looks in order. I tried hardcoding the shortcode with the URL, but it still doesn’t show up on the frontend. Is the URL in the correct embed format?
-
jgsearch
Hi Alvind, yes the URL is in the correct embed format. I just tried to hardcode now to a Headline block and the map works. An example page is https://freeairpumpsnearme.com/alaska/. The code you created still displays just the src URL. Could you please take a look on the settings again if something is still missing? Thanks!
-
Try replacing the snippet with this:
add_filter( 'render_block_generateblocks/headline', function( $block_content, $block ) { if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'dynamic-shortcode' ) !== false ) { $clean_content = strip_tags($block_content); $shortcode = do_shortcode('[iframe src="' . esc_url($clean_content) . '" width="100%" height="500"]'); return $shortcode; } return $block_content; }, 10, 2 );
-
jgsearch
Thank you so much! Maps are working now.
-
Alvind
Glad to hear that!
- You must be logged in to reply to this topic.