I have the following line that displays a message:
$added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
I would like to wrap teh message in a div, but I can’t work it out.
I have tried this, but it is outputting the actual HTML: $added_text = sprintf( _n( <div>' .'%s has been added to your cart.', '%s have been added to your cart.' .'</div>#, $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
Can anyone tell me how I can wrap the HTML in the string?
Remember that you need to put all the content inside the string. Meaning your tags need to be inside your single or double quotes. Also, note that _n() is a function that takes parameters for single and plural.
So you have two options. Either you put the div tags inside each of the parameters like so…
$added_text = sprintf( _n( '<div>%s has been added to your cart.</div>', '<div>%s have been added to your cart.</div>', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
Or better yet, you can use a single pair of tags for the entire sprintf…
$added_text = '<div>' . sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) ) . '</div>';
Which scenario you choose depends on if you want to have a different set tags for the single vs plural forms. But notice that in either scenario the tags are inside single quotes. Your example shows the tags outside the strings single quotes.
Thank you very much for the reply. I have tried both and both are outputting the <div> tags. For example: <div>“Product 1” has been added to your cart.</div>
You mentioned the example shows the tags outside of the quotes - is this why they are being outputted?
Yeah the function was probably trying to reconcile what the div tag itself meant versus the actual string in the single quotes. Strings are always using single or double quotes. Otherwise most functions have to guess if it is a string or not. In most cases they just crash with some “unknown type” or in the case of PHP which assumes a lot, it will guess and assume you are talking about a string.