jeudi 21 janvier 2021

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



Aucun commentaire:

Enregistrer un commentaire