Save WooCommerce Order Product Name to User Meta C

2019-02-26 06:50发布

Caveat: I'm a solo freelance designer not a developer ;-)

I've created a custom field in the Wordpress user meta called membership.

I've tried the following code to save the WooCommerce Product Name to the membership custom field on checkout with help from this answer.

Updated attempt:

function wascc_woocommerce_checkout_update_user_meta_membership ( $customer_id, $posted ) {

    if (isset($posted['$orderid'])) {
        $order = $posted['$orderid'];
    }
    $theorder = new WC_Order( $order );
    $items = $theorder->get_items();

    foreach ( $items as $item ) {
        $product_name = $item['name'];
    }

    if (!(empty($product_name))) {
        update_user_meta( $customer_id, 'membership', $product_name);
    }   

}

add_action( 'woocommerce_checkout_update_user_meta', 'wascc_woocommerce_checkout_update_user_meta_membership', 10, 2 );

It produces no error, but does not save the product name to membership.

Help appreciated.

Last question may be related.

1条回答
姐就是有狂的资本
2楼-- · 2019-02-26 07:24

as I've commented out, you should use woocommerce_checkout_update_order_meta.

Something like this:

function wascc_woocommerce_checkout_update_user_meta_membership ( $order_id ) {

    $theorder = new WC_Order( $order_id );
    $items = $theorder->get_items();

    foreach ( $items as $item ) {
        $product_name = $item['name'];
    }

    if (!(empty($product_name))) {

        // Gets the customer/user ID associated with the order. Guests are 0.
        $customer_id = $theorder->get_user_id();

        update_user_meta( $customer_id, 'membership', $product_name );

    }   

}

add_action( 'woocommerce_checkout_update_order_meta', 'wascc_woocommerce_checkout_update_user_meta_membership' );

I have doubts with your foreach loop though... you are looping just to get the last item?

查看更多
登录 后发表回答