I am having a bit of an issue right now with the VIP coding standards. I am trying to print out an admin notice as follows:
add_action( 'admin_notices', function() {
$class="notice notice-warning is-dismissible";
$message = __( 'We suggest that you use the <b>API Key file</b> for your API Keys.', 'package-wordpress' );
print wp_sprintf( '<div class="%s"><p>%s</p></div>', $class, $message );
});
It is successful in that it prints and displays the notice, however, when I run my code standards check, it throws escaping function errors.
----------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 1 LINE
----------------------------------------------------------------------
101 | ERROR | Expected next thing to be an escaping function (see
| | Codex for 'Data Validation'), not '$class'
101 | ERROR | Expected next thing to be an escaping function (see
| | Codex for 'Data Validation'), not '$message'
----------------------------------------------------------------------
I have done some research on this issue and found that it really wants me to escape the html when printing it to the screen, however when I do that, it of course removes the ability to have HTML inside of the message. What are the suggestions for doing this while still passing the coding standards?
1 Answer
One way you can handle this would be to do the wp_sprintf when assigning the value of the $message
variable and then use wp_kses
when you want to output. You could also output the div and paragraph tags before and after the message, which would eliminate the need for wp_sprintf
in this instance.
add_action( 'admin_notices', function() {
$message = __( 'We suggest that you use the <b>API Key file</b> for your API Keys.', 'package-wordpress' );
echo '<div class="notice notice-warning is-dismissible"><p>' . wp_kses( $message, array( 'b' => array() ) ) . '</p></div>';
});
If you wanted to keep it closer to the original you could do something like:
add_action( 'admin_notices', function() {
$class="notice notice-warning is-dismissible";
$message = wp_sprintf( __( '<div class="%s"><p>We suggest that you use the <b>API Key file</b> for your API Keys.</p></div>', 'package-wordpress' ), $class );
echo wp_kses( $message, array(
'div' => array( 'class' => array() ),
'p' => array(),
'b' => array(),
));
});