在用户admin中将复选框设置为自定义用户元 - WooCommerce

时间:2017-11-28 14:22:39

标签: php wordpress checkbox woocommerce admin

我在用户帐户管理界面中设置了一个简单的复选框字段。以下是我显示/保存它的方式:

function show_free_ground_field( $user ) { 
?>

    <h3>Free Ground Shipping</h3>

    <table class="form-table">

        <tr>
            <th>Free ground for order > $1000</th>

            <td>
                <?php
                woocommerce_form_field( 'freeGround', array(
                    'type'      => 'checkbox',
                    'class'     => array('input-checkbox'),
                    'label'     => __('Yes'),
                ), '' );


                ?>

            </td>
        </tr>

    </table>
<?php 
}
add_action( 'show_user_profile', 'show_free_ground_field' );
add_action( 'edit_user_profile', 'show_free_ground_field' );

function save_free_ground_field( $user_id ) {

    if ( !current_user_can( 'edit_user', $user_id ) ){
        return false;
    }
    if ( ! empty( $_POST['freeGround'] ) ){
        update_usermeta( $user_id, 'freeGround', $_POST['freeGround'] );
    }
}
add_action( 'personal_options_update', 'save_free_ground_field' );
add_action( 'edit_user_profile_update', 'save_free_ground_field' );

它显示正常,但如果我将其关闭并在保存后重新访问同一用户则取消选中该复选框。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要在第一个函数中获取此复选框字段的保存值:

add_action( 'show_user_profile', 'show_free_ground_field' );
add_action( 'edit_user_profile', 'show_free_ground_field' );
function show_free_ground_field( $user ) { 
    ?>
    <h3>Free Ground Shipping</h3>
    <table class="form-table">
        <tr>
            <th>Free ground for order > $1000</th>
            <td>
    <?php

    $freeGround = get_user_meta( $user->id, 'freeGround', true );
    if ( empty( $freeGround ) ) $freeGround = '';

    woocommerce_form_field( 'freeGround', array(
        'type'      => 'checkbox',
        'class'     => array('input-checkbox'),
        'label'     => __('Yes'),
    ), $freeGround );

    ?>
            </td>
        </tr>
    </table>
    <?php 
}

这应该现在可以使用