订单完成后更新用户字段

时间:2013-11-12 05:25:56

标签: wordpress woocommerce

任何人都可以帮我解决这个问题。我曾经让它一次工作,但由于WooCommerce的一些变化,它不再有效。

代码必须在订单完成时运行,并根据他们从购买中获得的积分来更新用户元字段。

由于

 function custom_update_user_credits( $order_id = NULL ) {
    global $woocommerce;


    // Set product ids and credits

    $product_id1 = 80;
    $ad_credits1 = 10;

    $product_id2 = 82;
    $ad_credits2 = 20;

    $product_id3 = 83;
    $ad_credits3 = 30;


    $customer_id = get_post_meta( $order_id, '_customer_user', TRUE );
    $user_credit = (int) get_user_meta( $customer_id, 'wpcf-ad_credits', TRUE );

    if ( $order_id && 0 != $customer_id ) :
        $order = &new WC_Order( $order_id );


        // Get the order items

        $items = get_product( $post->ID );

        // Loop through the order items looking for the right products
        foreach($items as $item) :


            // Credits

            if ( $item['id'] == $product_id1 ) :
            $credit_total = $user_credit + $ad_credits1;

            elseif ( $item['id'] == $product_id2 ) :
            $credit_total = $user_credit + $ad_credits2;

            elseif ( $item['id'] == $product_id3 ) :
            $credit_total = $user_credit + $ad_credits3;

            update_user_meta( $customer_id, 'wpcf-ad_credits', $credit_total, $user_credit );                       

            endif;

        endforeach;

    endif;

}

add_action( 'woocommerce_order_status_completed', 'custom_update_user_credits' );

1 个答案:

答案 0 :(得分:0)

在尝试解决自己的问题时,我不止一次地遇到过这个问题。这可能有点晚了,但我在这里使用woocommerce产品数据更新自定义用户元数据。

add_action( 'woocommerce_payment_complete', 'CUSTOM_AFTER_PURCHASE_FUNCTION' );

function CUSTOM_AFTER_PURCHASE_FUNCTION( $order_id ) {

    // Get user's ID
    $order_user_id = get_post_meta( $order_id, '_customer_user', true );

    // If there's a valid order and user continue
    if ( $order_id && $order_user_id != 0 ) {

        // Get $order
        $order = new WC_Order($order_id);

        // Loop through $order items
        foreach( $order->get_items() as $item ) {

            // Get product info using $item['product_id']
            $product = new WC_Product($item['product_id']);

            // Get $sku ... I explode it into an array because I have info mapped to it
            $sku_array = explode('-', $product->get_sku());
            if ( $sku_array[0] == 'CR' )
                $credits_to_add = $sku_array[1] * $item['qty'] + $credits_to_add;
        }

        $new_credit_count = users_current_credits() + $credits_to_add; // Uses custom function to check user's current credits
        update_user_meta( $order_user_id, 'contest-credits', $new_credit_count );

    }
}

希望这会有所帮助