Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

wordpress - Set checkbox checked by default in PHP

I have a checkbox in the dashboard of my headless WordPress, which allows users to toggle a feature on the frontend view. However, I need the checkbox that controls the feature to load as checked by default, even if the value isn't in the database yet. If the user clicks the checkbox off, it will uncheck the feature, and then the user can select it again to check it.

I'm trying to use a simple ternary to check the existence of the value in the database and if it exists, set the property checkbed on the checkbox, otherwise the checkbox should be unchecked.

However, I'm having an issue with the logic and PHP syntax to get this to work properly. What am I missing, that is causing the dashboard to render checked value="1" checked='checked' /> instead of the checkbox itself?

$option_toggled = get_option( 'option_toggle' );

echo '<input type="checkbox" name="option_toggle" ' . $option_toggled === '1' ? 'checked' : null . ' value="1" ' . checked( get_option( 'option_toggle' ), 1, false ) . ' />';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your issue is because of the null parameter you're adding to the ternary. Either set it as an empty string, or wrap your ternary operator in parentheses:

echo '<input type="checkbox" name="option_toggle" ' . ($option_toggled === '1' ? 'checked' : null) . ' value="1" ' . checked( get_option( 'option_toggle' ), 1, false ) . ' />';

That having been said, why not just let the checked() function do this, since it appears to be doing that already?

echo '<input type="checkbox" name="option_toggle" '.checked(get_option('option_toggle'), 1, false).' />';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...