Categories
Filter Shortcode

How to execute shortcode in any string or custom field in WordPress

You can use WordPress filter the_content and apply it to any string or custom field data to display its HTML content as well as render or execute any shortcode in it.

Here is a code snippet, where a string with some HTML content and a shortcode in it.

// $data is defined as a string with HTML code as well as WordPress shortcode in it
$data = '<div class="custom-html-code"> <h2> Here is a list of Recent Posts</h2> [recent-posts posts="5"]</div>';
echo apply_filters( 'the_content', $data); 

The above code will not just display the HTML code, But also when it encounters the [recent-posts] shortcode, it will execute it. It will also apply any other filter that has been applied to the_content filter.

Now let’s say, you have a custom Textarea field that you created using ACF ( advanced custom fields plugin) in your custom post, and it has HTML data as well as shortcodes. In that case, you can use code as shown in the example below.

// CODE FOR ACF CUSTOM FIELD
echo apply_filters( 'the_content', get_field("field_name_here") ); 

// CODE FOR Other custom field using post meta data function
echo apply_filters( 'the_content', get_post_meta($post->ID,"field_name_here",true) ); 

By Murali Kumar

I am a Full Stack Web Developer with over 12 years of experience. I love WordPress & WooCommerce.

If you need help of a WordPress developer for your website, get in touch now!.

Follow me on Twitter : @geekz

Leave a Reply

Your email address will not be published. Required fields are marked *