Tag: Custom Field

  • 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) );