Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k 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 Reply

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).' />';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...