1

hi all i need create to metabox in page for the footer and header posttypes i created, in this code i tried for this but i cant save selected item and retrive id selected item in the frontend.

function wpdocs_register_meta_boxes() {
    add_meta_box( 'meta-box-id', __( 'header', 'textdomain' ),'wpdocs_my_display_callback', 'page', 'normal' , 'high');
}
add_action( 'add_meta_boxes', 'wpdocs_register_meta_boxes' );
 

function wpdocs_my_display_callback() {

    ?>

    <select name="count" id="selectId" >
    <?php  

    $posts = new WP_Query(array('posts_per_page' => -1, 'post_type' => 'header')); 
    while($posts->have_posts()) : $posts->the_post(); ?>
       <option id="selection" value="<?php echo get_the_ID(); ?>"><?php echo get_the_title(); ?></option>
    <?php endwhile;
    die()
    ?>
    </select>
   <?php 
}
 

function wpdocs_save_meta_box( $post_id ) {


    if (isset($_POST['selectId'])) {

        update_post_meta( $post_id, 'selectId', $_POST['selectId']);
    }


}
add_action( 'save_post', 'wpdocs_save_meta_box' );
0

There are few problems with your code.

First,

The name of the select field is not the same as you are trying to save using the global variable $_POST. You are saving $_POST['selectId'] data but it does not exist in your meta box. You named the select field as "count" but trying to get value using "selectId" key.

Second,

You need to get the saved value and use it to compare with the select field value to be selected.

Your wpdocs_my_display_callback function will be like this to set the selected value.

    function wpdocs_my_display_callback()
    {
        global $post;
        $saved_value = get_post_meta($post->ID, 'selectId', true);
    ?>
    
        <select name="selectId" id="selectId">
            <?php
    
            $posts = new WP_Query(array('posts_per_page' => -1, 'post_type' => 'header'));
            while ($posts->have_posts()) : $posts->the_post(); ?>
                <option <?php selected($saved_value, get_the_ID()); ?> id="selection" value="<?php echo get_the_ID(); ?>"><?php echo get_the_title(); ?></option>
            <?php endwhile;
            // die()
            ?>
        </select>
    <?php
    }

I think it will work for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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