WooCommerce:管理员中的动态自定义结帐字段

时间:2016-07-19 16:13:42

标签: php wordpress woocommerce checkout custom-fields

我在向订单管理员添加自定义结帐字段时遇到问题(可能还有电子邮件,我还没有)。除了编码问题,我大部分时间都遵循https://www.kathyisawesome.com/woocommerce-customize-checkout-fields/ - 到目前为止我的代码:

http://pastebin.com/y8LDcDxS

我添加' x'假定购物车中有一个产品,基于产品数量的$ fields [' extra_fields']金额。我正在与kia_display_order_data_in_admin()进行斗争 - 无论我做什么,我都会一直在get_country()。我已经在pastebin中获得了非动态变化(基于购物车中有两个产品) - 我试图让这部分动态的其他一切都无法正常工作。

我看到一些选项可以在管理员中加载这些动态字段,但我无法到达那里:

  1. 再次获取产品数量并将$ i附加到标准字段名称的末尾

  2. 以某种方式获取所有字段的数组,以便我可以提取$ fields [' extra_fields']

  3. 通过order_id

  4. 获取extra_fields post meta
  5. 还有别的吗?

  6. 编辑:在Kia的帮助下,我对代码进行了一些修改,现在它将动态添加自定义结帐字段。这一直一直运行到管理员订单屏幕,但在尝试更新管理员rtspcsrc

    中的订单详细信息时却无法正常工作

    编辑2:请参阅下面接受的答案,因为这适用于我的问题

1 个答案:

答案 0 :(得分:4)

您确定Product Add-Ons可能不适合这个吗?如果没有,我认为你需要的是自定义输入类型。这应该可以帮到你。

/* Add a new checkout field 
 * 
 * These is our base field group, later on, depending on product quanitiy, $key = 'passenger_title_1' for example
 * 
 */

function supreme_filter_checkout_fields($fields){
    $fields['extra_fields'] = array(
    'passenger_details' => array(
        'type' => 'passenger_details',
        'required'      => false,
        'label' => __( 'Passenger Details' )
        ),
    );

    return $fields;

}
add_filter( 'woocommerce_checkout_fields', 'supreme_filter_checkout_fields' );

什么是" passenger_details"输入?好吧,我们要定义这一点,因为woocommerce_form_field()有一个问题,以防该类型与WooCommerce的任何默认设置都不匹配。见'woocommerce_form_field_' . $args['type']

以下是我们要为每位乘客列出您想要的字段组的地方。

function supreme_filter_checkout_field_group( $field, $key, $args, $value ){
    $op_cart_count = WC()->cart->get_cart_contents_count();

    $html = '';

    for ( $i = 1; $i <= $op_cart_count; $i++) {

        $html .= woocommerce_form_field( "passenger_details[$i][title]", array( 
            "type" => "select",
            "return" => true,
            "value" => "",
            "options" => array( "mr" => __( "Mr" ), "mrs" => __( "Mrs" ), "miss" => __( "Miss" ) ),
            "required"      => false,
            "label" => __( "Title" )
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][first_name]", array(
            "type" => "text",
            "return" => true,
            "value" => "",
            "required"      => false,
            "label" => __( "First Name" )
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][middle_name]", array(
            "type" => "text",
            "return" => true,
            "value" => "",
            "required"      => false,
            "label" => __( "Middle Name" )
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][last_name]", array(
            "type" => "text",
            "return" => true,
            "value" => "",
            "required"      => false,
            "label" => __( "Last Name" )
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][date_of_birth]", array(
            "type"          => "text",
            "return" => true,
            "value" => "",
            "class"         => array("date-of-birth form-row-wide"),
            "required"      => false,
            "label"         => __("Date of Birth"),
            "placeholder"       => __("Select Date"),
            "options"     =>   array("" => __("Date of Birth", "woocommerce" ))
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][dietary_required]", array(
            "type" => "select",
            "return" => true,
            "value" => "",
            "class"         => array("dietary-required form-row-wide"),
            "options" => array( "" => __( "Please Select" ), "y" => __( "Yes" ), "n" => __( "No" ) ),
            "required"      => false,
            "label" => __( "Dietary Requirements?" )
            )
        );
        $html .= woocommerce_form_field( "passenger_details[$i][dietary_preference]", array(
            "type" => "select",
            "return" => true,
            "value" => "",
            "class"         => array("dietary-requirements form-row-wide"),
            "options" => array( "v" => __( "Vegetarian" ), "GF" => __( "Gluten Free" ) ),
            "required"      => false,
            "label" => __( "Meal Preferences" )
            )
        );

    }
    return $html;
}
add_filter( 'woocommerce_form_field_passenger_details', 'supreme_filter_checkout_field_group', 10, 4 );



// display the extra field on the checkout form
function supreme_extra_checkout_fields(){ 

    $checkout = WC()->checkout();

    foreach ( $checkout->checkout_fields['extra_fields'] as $key => $field ) :

        woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );

    endforeach;


}
add_action( 'woocommerce_checkout_after_customer_details' ,'supreme_extra_checkout_fields' );

编辑处理清理和保存数据。请注意,我更改了上面的supreme_filter_checkout_field_group函数并删除了ID参数。

~~使用id参数,我们可以动态设置输入名称。生成的标记应该类似于:~~

<input type="text" class="input-text " name="last_name" id="passenger_details[2]last_name" placeholder="" value="">

这是错的。 name参数需要是一个数组!名称是从woocommerce_form_field()的第一个参数中提取的。 ID与我们的需求无关,但需要保持唯一以保持正确的标记。这是我们需要的结果,现在应该通过上述修改得到:

<input type="text" class="input-text " name="passenger_details[2][last_name]" id="passenger_details[2][last_name]" placeholder="" value="">

现在提交时,$_POST['passenger_data']应该是数组的阵列(乘客)(乘客详情)。在我编辑之后,它就是!

现在,为了处理这些数据并清理乘客数据中的各个字段,我们创建了一个清理自定义字段类型的功能:

/**
 * Sanitize our custom field
 * 
 */
function supreme_custom_process_checkout_field_passenger_details( $posted ){

    $clean = array();

    foreach( $posted as $passenger ){
        $details = supreme_custom_checkout_clean_passenger_details( $passenger );

        if( ! empty( $details ) ){
            $clean[] = $details;
        }
    }

    return $clean;
}
add_filter( 'woocommerce_process_checkout_passenger_details_field', 'supreme_custom_process_checkout_field_passenger_details' );


function supreme_custom_checkout_clean_passenger_details( $passenger = array() ){
    $details = array();
    if( isset( $passenger["title"] ) ){
        $details['title'] = sanitize_text_field( $passenger["title"] );
    }
    if( isset( $passenger["first_name"] ) ){
        $details['first_name'] = sanitize_text_field( $passenger["first_name"] );
    }
    if( isset( $passenger["middle_name"] ) ){
        $details['middle_name'] = sanitize_text_field( $passenger["middle_name"] );
    }
    if( isset( $passenger["last_name"] ) ){
        $details['last_name'] = sanitize_text_field( $passenger["last_name"] );
    }
    if( isset( $passenger["date_of_birth"] ) ){
        $details['date_of_birth'] = $date = preg_replace("([^0-9/])", "", $passenger["date_of_birth"] );
    }
    if( isset( $passenger["dietary_required"] ) ){
        $details['dietary_required'] = $passenger["dietary_required"] == "y" ? "y": "n";
    }
    if( isset( $passenger["dietary_preference"] ) && isset( $passenger["dietary_required"] ) && $passenger["dietary_required"] == "y" ){
        $details['dietary_preference'] = $passenger["dietary_preference"] == "GF" ? "GF": "v";
    }
    return $details;
}

现在已经消毒了,更新只是保存帖子元素的问题:

/**
 * update_post_meta
 * 
 */
function supreme_custom_checkout_field_update_order_meta( $order_id, $posted ){

    if( ! empty( $posted["passenger_details"] ) ){
        update_post_meta( $order_id, "_passenger_details", $posted["passenger_details"] );
    } else {
        delete_post_meta( $order_id, "_passenger_details" );
    }

}
add_action( 'woocommerce_checkout_update_order_meta', 'supreme_custom_checkout_field_update_order_meta', 10, 2 );

现在,我们肯定已将所有字段保存在_passenger_details post元组密钥中,并且我们可以在需要显示它时循环遍历该数组。例如,它位于管理员订单页面上:

// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order ){  

    $passenger_details = get_post_meta( $order->id, "_passenger_details", true ); 

    if( ! empty( $passenger_details ) ) { 

        $passenger_defaults = array(
                "title" => "",
                "first_name" => "",
                "middle_name" => "",
                "last_name" => "",
                "date_of_birth" => "",
                "dietary_required" => "",
                "dietary_preference" => ""
            );

    ?>
    <div class="passenger_data">
        <h4><?php _e( "Passenger Details", "your-slug" ); ?></h4>
        <?php 
            $i = 1;

            foreach( $passenger_details as $passenger ){

                $passenger = wp_parse_args( $passenger, $passenger_defaults );

                echo "<p><strong>" . sprintf( __( "Passenger #%s", "your-slug" ), $i  ) . "</strong>" . "<br/>";
                echo __( "Title", "your-slug" ) . ' : ' . $passenger["title"] . "<br/>";
                echo __( "First Name", "your-slug" ) . ' : ' . $passenger["first_name"] . "<br/>";
                echo __( "Middle Name", "your-slug" ) . ' : ' . $passenger["middle_name"] . "<br/>";
                echo __( "Last Name", "your-slug" ) . ' : ' . $passenger["last_name"] . "<br/>";
                echo __( "Date of Birth", "your-slug" ) . ' : ' . $passenger["date_of_birth"] . "<br/>";
                echo __( "Dietary Required", "your-slug" ) . ' : ' . $passenger["dietary_required"] . "<br/>";
                echo __( "Dietary Preference", "your-slug" ) . ' : ' . $passenger["dietary_preference"] . "<br/>";

                echo "</p>";

                $i++;

            }

         ?>
    </div>
<?php }
}
add_action( "woocommerce_admin_order_data_after_order_details", "kia_display_order_data_in_admin" );

现在仍然留下了谢谢你的页面和电子邮件,但数据就在那里。