0

In my theme, i am grabbing user input with get_option() and according to that input i want to i want to declare a new variable and print in my single.php file. For example:

<?php
$tutorial_condition = get_option( 'tutorials_creater' );

if ( $tutorial_condition == 1 ) {
    $second_col_class = 'col-9';
} else {
    $second_col_class = 'col-2';
}
?>

now when i echo $second_col_class variable in my php files it works fine. But when i run themecheck plugin it shows an error like this.

"Possible data validation issues found. All dynamic data must be correctly escaped for the context where it is rendered."

i want to echo that variable like below.

 <div class="<?php echo $second_col_class; ?>">
     //my code here..
 </div>

I cannot use isset() function because it just returning true or false. Is there any alternative to this?

1 Answer 1

1

Please see this Codex article for further guide, but in your case, you would use esc_attr() to escape the $second_col_class value which is being used in an HTML attribute, namely class:

<!-- bad -->
<div class="<?php echo $second_col_class; ?>">

<!-- good -->
<div class="<?php echo esc_attr( $second_col_class ); ?>">

<!-- good -->
<div class="<?php esc_attr_e( $second_col_class, 'text-domain' ); ?>">
3
  • Problem solved.thanks. But even this variable value is not a user input, why WordPress recommend to use esc_attr() function.
    – Sahan
    Commented Nov 4, 2020 at 9:10
  • Because it's a good practice to always escape values that are dynamic, e.g. strings assigned to a variable like your $second_col_class - what if someone edited your code and changed the value to a dynamic one, like another variable? And if my answer answered the question, please consider marking the answer as correct. =) Thanks!
    – Sally CJ
    Commented Nov 4, 2020 at 9:39
  • If you're specifically asking about the esc_attr(), then as I said in my answer and by the function's purpose itself, WordPress recommends using it because that's one of the correct functions we should use for escaping HTML attributes like class, title and src. :)
    – Sally CJ
    Commented Nov 4, 2020 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.