0

Can anyone help me with this code. I had it working at one time but due to some changes in WooCommerce it no longer works.

The code must run on order completion and update the users meta field based on how many credits they earned from the purchase.

Thanks

 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' );
4

1 回答 1

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 );

    }
}

希望这会有所帮助

于 2014-03-12T20:09:51.207 回答