Wordpress自定义字段单选按钮无法选中

Wordpress Custom field Radio Button cant checked

本文关键字:单选按钮 自定义 字段 Wordpress      更新时间:2023-09-26

我一直在尝试在我的领域做一个单选按钮,像这样:

function orderMB_meta_box_output( $post ) {
  // create a nonce field
  wp_nonce_field( 'my_orderMB_meta_box_nonce', 'orderMB_meta_box_nonce' ); ?>
 <p>
        <label><b>Status Order :</b></label>
        <br />  
        <input type="radio" name="status_order" value="Process Packing" <?php echo ($value[0] == 'Process Packing')? 'checked="checked"':''; ?> >Process Packing<br>
        <input type="radio" name="status_order" value="Shipping" <?php echo ($value[0] == 'Shipping')? 'checked="checked"':''; ?> >Shipping<br>
        <input type="radio" name="status_order" value="Arrive" <?php echo ($value[0] == 'Arrive')? 'checked="checked"':''; ?> >Arrive<br>
        <input type="radio" name="status_order" value="Success" <?php echo ($value[0] == 'Success')? 'checked="checked"':''; ?> >Success<br>
    </p>
  <?php
}
function orderMB_meta_box_save( $post_id ) {
  // Stop the script when doing autosave
  if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
  // Verify the nonce. If insn't there, stop the script
  if( !isset( $_POST['orderMB_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['orderMB_meta_box_nonce'], 'my_orderMB_meta_box_nonce' ) ) return;
  // Stop the script if the user does not have edit permissions
  if( !current_user_can( 'edit_post' ) ) return;
   update_post_meta( $post_id, 'orderno', esc_attr( $_POST['orderno'] ) );
 $allowed = array('Process Packing','Shipping','Arrive','Success');
 if( isset( $_POST['status_order'] )  && in_array($_POST['status_order'], $allowed))
    update_post_meta( $post_id, 'status_order', esc_attr( $_POST['status_order'] ) );
}
add_action( 'save_post', 'orderMB_meta_box_save' );

我认为我的代码是正确的,它的工作,但在为什么我的单选按钮不检查。

有人来帮我吗?

您错过了从数据库中获取值的行,该值存储在当前的post id..

$status_order = get_post_meta( $post->ID, 'status_order', true );

你的函数应该有上面的行来获取值&通过var_dump()检查。删除var_dump如果值是完美显示/检查你的单选按钮。

function orderMB_meta_box_output( $post ) {
  // create a nonce field
  wp_nonce_field( 'my_orderMB_meta_box_nonce', 'orderMB_meta_box_nonce' ); 
    $status_order = get_post_meta( $post->ID, 'status_order', true );
    var_dump($status_order); // dump to check database value
    ?>
 <p>
        <label><b>Status Order :</b></label>
        <br />
        <input type="radio" name="status_order" value="Process Packing" <?php echo ($status_order == 'Process Packing')? 'checked="checked"':''; ?> >Process Packing<br>
        <input type="radio" name="status_order" value="Shipping" <?php echo ($status_order == 'Shipping')? 'checked="checked"':''; ?> >Shipping<br>
        <input type="radio" name="status_order" value="Arrive" <?php echo ($status_order == 'Arrive')? 'checked="checked"':''; ?> >Arrive<br>
        <input type="radio" name="status_order" value="Success" <?php echo ($status_order == 'Success')? 'checked="checked"':''; ?> >Success<br>
    </p>
  <?php
}