How to Generate html tags using shortcodes?

Your shortcode is designed to print results directly on the page so it isn’t possible to first check if the output is empty before printing. However, the shortcode runs a specific function and you can use that function directly in a couple ways.

  • Method 1: You can add some additional PHP logic to your template code.
  • Method 2: You can create a custom shortcode with the additional HTML you need.

The function used by [acf field=”something”] is called the_field(). Like I mentioned above the_field() prints directly to the page which doesn’t work for your purposes. Instead you can use get_field() and print it when you choose.

Using get_field() is very similar to using the shortcode. It accepts two parameters; 1. the name of the field, and 2. the post ID.

get_field('FieldName','ID')

Method 1

Some simple PHP logic to check if the value is empty before printing to the page would look like this.

<?php
$testimony_text = get_field('testimony', $post->ID );
$testimony_name = get_field('name', $post->ID );
if ( $testimony_text != '' && $testimony_name != '' ) {
    echo "<h4>{$testimony_text} <strong>{$testimony_name}</strong></h4>";
}
?>

Method 2

A custom shortcode that wraps your HTML around the output might look like this. Place this in your theme’s functions.php file.

function acfcustom_func($atts) {
       extract( shortcode_atts( array(
        'text' => '',
        'name' => '',
    ), $atts ) );

    $id = get_the_id();
    $testimony_text = get_field($text, $id );
    $testimony_name = get_field($name, $id );

    if ( $testimony_text == '' || $testimony_name == '' ) return; 

    $output = "<h4>{$testimony_text} <strong>{$testimony_name}</strong></h4>";

    return $output;
}
add_shortcode( 'acfcustom', 'acfcustom_func' );

To use the shortcode paste it in your post body or sidebar widget like this.

[acfcustom text="testimonial" name="name"]

NOTE: A shortcode won’t normally work in a sidebar widget but this can be changed. There are plugins available that makes it possible to run shortcodes in sidebar widgets.

Description of how method 2 works

This could get really long really fast. Here’s a quick overview.
Ok, so we first build a simple shortcode function. The WordPress Codex has some examples here. We pass into the function the $atts array which holds the parameters (testimonial and name) we are going to specify in the shortcode. We then extract the parameters from the $atts array and specify variable names for them. Now we can use the parameters in the get_field() function. The function is specific to the Advanced Custom Fields plugin you are using. The results of get_field() are set to new variables ($testimony_text and $testimony_name). Now using some IF logic we check if either of the variables is empty. If it is we end the function and return nothing. If both variables have content we concatenate them into the HTML string and then return the string to be printed on the page.