Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k 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 ) . ' />';
question from:https://stackoverflow.com/questions/65834537/set-checkbox-checked-by-default-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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 OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...