Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've created a simple meta box consisting of two radio buttons: yes or no.

When they click on the appropriate box, it saves the meta value to the database. However, the post page does not remember it has done this: whichever radio button was pressed, the 'checked' value is no longer there.

Below is the code. What is the best way to save the 'checked' state — so the user will know which was checked?

## ADD TOP META BOX

function top_custom_meta(){
    add_meta_box('top_meta', 'Is this a top post?', 'top_meta_callback', 'post', 'side', 'high');
}

add_action('add_meta_boxes', 'top_custom_meta');

## OUTPUTS TOP CONTENT 

function top_meta_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'top_nonce' );
    $top_stored_meta = get_post_meta( $post->ID ); ?>
            <div>
        <label>
            <input type="radio" name="top-radio" value="radio-one-a">
            <?php echo 'Yes' ?>
        </label>
            </div>

            <div>
        <label>
            <input checked="checked" type="radio" name="top-radio" value="radio-two-b">
             <?php echo 'No' ?>
        </label>
      </div>

    <?php
}

# SAVE TOP OUTPUT TO DATABASE

function top_meta_save( $post_id ) {

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'top_nonce' ] ) && wp_verify_nonce( $_POST[ 'top_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
        return;
    }

    // Checks for input and sanitizes/saves if needed
    if( isset( $_POST[ 'top-radio' ] ) ) {
        update_post_meta( $post_id, 'top-radio', sanitize_text_field( $_POST[ 'top-radio' ] ) );
    }

}
add_action( 'save_post', 'top_meta_save' );

I basically need to add checked="checked" to whichever radio button was pressed.

share|improve this question
    
This guide will show you exactly what you need. See the Radio buttons sections, it's really well explained. themefoundation.com/wordpress-meta-boxes-guide –  gdaniel Mar 13 at 20:36

1 Answer 1

WP provides checked() helper to be used in forms. For every choice you need to call it providing current (saved) state and value of current choice. From that it will produce checked markup for the match.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.