简体   繁体   中英

WordPress PHP checkbox checked by default

I did search this and found some examples and answers, but not being much of a coder, I really didn't understand the solutions since the code looked different than mine.

I have a WP theme that has a few option checkboxes in the Add Post page. I'd like one checkbox to be checked by default:

array(
        'name' => 'Show in Front Page Heading Slider',
        'id' => $prefix . 'fps',
        'type' => 'checkbox'
    ),

Obviously I need to add the checked value here, but my attempts haven't worked. Any ideas?

I think you need this: <?php checked( $checked, $current, $echo ); ?> <?php checked( $checked, $current, $echo ); ?>

<?php

// Get an array of options from the database.
$options = get_option( 'slug_option' );

// Get the value of this option.
$checked = $options['self-destruct'];

// The value to compare with (the value of the checkbox below).
$current = 1; 

// True by default, just here to make things clear.
$echo = true;

?>
<input name="slug-option[self-destruct]" value="1" <?php checked( $checked, $current, $echo ); ?>/>

Testing the value with if():

<input type='checkbox' name='options[postlink]' value='1' <?php if ( 1 == $options['postlink'] ) echo 'checked="checked"'; ?> />

Using checked() instead:

<input type="checkbox" name="options[postlink]" value="1" <?php checked( $options['postlink'], 1 ); ?> />

Take a look on this link for more info: https://codex.wordpress.org/Function_Reference/checked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM