Using Global Blocks with ACF plugin

Hello guys. Is it possible to add content from custom fields to the Global Blocks?

I’m using custom fields in my php files like:

   <?php 
        $image = get_field('image_1');
		if( !empty($image) ): ?> 
<div style="background-image: url('<?php echo $image; ?>');"></div>
        <?php endif; ?>

And it works great for me. I would love to add similar feature to my Global Blocks. How can I do that? Thanks for your help!

Hello Denys,

Thanks for asking. :slight_smile:

Please take a look at following article for some help.

https://michaelbourne.ca/global-blocks-acf-pro-cpt-template/

Thanks.

Hey Prasant,

Thanks for the fast response. I’ve read this article before submitting the question. Nothing works to me. I’ve tried to add both images and text to Global Blocks but it displays just a line in curly braces. Do you have some other ideas how can I manage the problem?
Can you explain me please what does it mean V2 elements?

Regards,
Denys

Hi Denys,

You can create your custom shortcode then add it to your global block.

The code should be like this:

add_shortcode( 'acf_images', 'function_acf_images' );
function function_acf_images(){

	$image = function_exists('get_field') ? get_field('image_1') : '';

	ob_start();

	if( !empty($image) ): ?> 
		<div style="background-image: url('<?php echo $image; ?>');"></div>
    <?php endif;

	$content = ob_get_clean();

	return $content;
}

Then you can use the [acf_images] shortcode anywhere.

For more information, please take a look at this:

https://codex.wordpress.org/Shortcode_API

Hope it helps :slight_smile:

1 Like

You are the best! It works like a charm!
I have one more question. Hope it’s the last one. If I have multiple acf images, can I use just one shortcode with different attributes to return them? So, for example, I use [acf_images image1] to display my first image and [acf_images imageX] to display another one. Thanks for your help!
Regards,
Denys

Hi Denys,

Please update the previous code to this:

add_shortcode( 'acf_images', 'function_acf_images' );
function function_acf_images($atts){
	extract( shortcode_atts( array(
		'field' => '',
	), $atts, 'acf_images' ) );

	$image = function_exists('get_field') ? get_field($field) : '';

	ob_start();

	if( !empty($image) ): ?> 
		<div style="background-image: url('<?php echo $image; ?>');"></div>
    <?php endif;

	$content = ob_get_clean();

	return $content;
}

So you can use the shortcode like this: [acf_images field="image1"] and [acf_images field="image2"]

Hope it helps :slight_smile:

1 Like

Hi Thai,

Sorry for the late response. Amazing solution! Thank you a lot!

Sincerely,
Denys

You’re welcome, Denys. Just note that there are built-in ACF Shortcodes available. See https://www.advancedcustomfields.com/resources/shortcode/

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.