简体   繁体   中英

How can I add a css class to my example php code

Idd like to add a class within the output of this piece of php code

function acf_esg_tax_field_loc( $atts, $content = null ) {
    $a = shortcode_atts(array('post_id' => "1"), $atts);
    $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );

    echo $term->name;
}

add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

The code is used in my Wordpress functions php to generate a shortcode.

It should be something like this

function acf_esg_tax_field_loc( $atts, $content = null ) {
    $a = shortcode_atts(array('post_id' => "1"), $atts);
    $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );

    echo '<div class="OutputClass" >';
    echo $term->name;
    echo '</div>'; 
}

add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

Unfortunatly this does not work.

Can you please help?

As the WordPress Code Reference states.

Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.

So first change it from echo to one return. You could define a variable, concatenate to it and finally return it.

Result:

function acf_esg_tax_field_loc( $atts, $content = null ) {
    $a = shortcode_atts(array('post_id' => "1"), $atts);
    $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );

    $sR =  '<div class="OutputClass" >';
    $sR .= $term->name;
    $sR .= '</div>'; 
    return $sR;
}

add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

If the class is always the same and thus could be hardcoded, then you are very close. Only one echo will be outputted, so concatenate it:

echo '<div class="OutputClass" >'.$term->name.'</div>';

If it's dynamic and you need to get the class name somewhere and pass it along, then that's a whole different story.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM