Put a span tag inside specific WooCommerce checkout field wrapper html tag

Viewed 395

I'm trying to put a <span> tag inside of the <p> wrapper tag on checkout page for shipping city field. I have tried so much different ways, but all of them have failed.

Here is my code attempt (doesn't work):

function hackies( $field, $key, $args, $value ) {

// Wrap all fields except first and last name.
if ( $key === 'shipping_city' ) {
    $field .= '<span>hello world</span>';
}

return $field;
}
add_filter( 'woocommerce_form_field_text', 'hackies', 10, 4);

But it's not working, anyone could help with this?

1 Answers

You are not using the right hook and the right way. Using PHP str_replace() function in a hooked function using woocommerce_form_field filter hook do the job:

add_filter( 'woocommerce_form_field', 'hackies', 10, 4);
function hackies( $field, $key, $args, $value ) {
    // Wrap all fields except first and last name.
    if ( $key === 'shipping_city' ) {
        $field = str_replace( array('<label ', '</span>'), array('<span class="special"><label ', '</span></span>'), $field );
    }
    return $field;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

This works for "input text" fields type… It requires something a bit different for other fields types.

Related