Bird
0
0

You want to save a user preference 'font_size' only if it is a positive integer. Which code snippet correctly updates the setting safely?

hard📝 Application Q15 of 15
Wordpress - WordPress Settings and Configuration
You want to save a user preference 'font_size' only if it is a positive integer. Which code snippet correctly updates the setting safely?
A<pre>update_option('font_size', $_POST['font_size']);</pre>
B<pre>$size = intval($_POST['font_size']); if ($size > 0) { update_option('font_size', $size); }</pre>
C<pre>if ($_POST['font_size']) { update_option('font_size', $_POST['font_size']); }</pre>
D<pre>$size = $_POST['font_size']; update_option('font_size', $size > 0 ? $size : 12);</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Validate and sanitize the input

    $size = intval($_POST['font_size']);
    if ($size > 0) {
      update_option('font_size', $size);
    }
    uses intval to convert input to integer and checks if it is positive before saving.
  2. Step 2: Confirm safe update of option

    Only if the value is positive does it call update_option, preventing invalid data.
  3. Final Answer:

    $size = intval($_POST['font_size']);
    if ($size > 0) {
    update_option('font_size', $size);
    }
    -> Option B
  4. Quick Check:

    Validate input before update_option [OK]
Quick Trick: Always validate input before update_option [OK]
Common Mistakes:
  • Saving raw user input without validation
  • Using update_option without checking value
  • Assuming non-empty input is always valid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Wordpress Quizzes