簡體   English   中英

在WooCommerce中購買產品后,將相關的訂單ID添加為用戶元數據

[英]After purchasing a product in WooCommerce add the related order ID as user metadata

購買產品后,在此用戶元數據中添加此產品訂單ID。 我可以使用此wc_customer_bought_product()檢查產品的購買狀態。 現在,我需要使用用戶ID和產品ID獲取此產品訂單ID。 我該如何實現? 我的最終目標是在獲得訂單ID之后,我將通過此函數wp_delete_post()刪除訂單

$bronze = wc_customer_bought_product($current_user->user_email, $current_user->ID, 246014);

function get_customerorderid(){
    global $post;
    $order_id = $post->ID;

    // Get an instance of the WC_Order object
    $order = wc_get_order($order_id);

    // Get the user ID from WC_Order methods
    $user_id = $order->get_user_id(); // or $order->get_customer_id();

    return $user_id;
}
get_customerorderid();
wp_delete_post(246014,true);

您可以通過以下方式使用WPDB類將自定義sql查詢嵌入函數中:

function get_completed_orders_for_user_from_product_id( $product_id, $user_id = 0 ) {
    global $wpdb;

    $order_status = 'wc-completed';

    // If optional $user_id argument is not set, we use the current user ID
    $customer_id = $user_id === 0 ? get_current_user_id() : $user_id;

    // Return customer orders IDs containing the defined product ID
    return $wpdb->get_col( $wpdb->prepare("
        SELECT DISTINCT woi.order_id
        FROM {$wpdb->prefix}posts p
        INNER JOIN {$wpdb->prefix}postmeta pm
            ON p.ID = pm.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items woi
            ON p.ID = woi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta woim
            ON woi.order_item_id = woi.order_item_id
        WHERE p.post_status = '%s'
        AND pm.meta_key = '_customer_user'
        AND pm.meta_value = '%d'
        AND woim.meta_key IN ( '_product_id', '_variation_id' )
        AND woim.meta_value LIKE '%d'
        ORDER BY woi.order_item_id DESC
    ", $order_status, $customer_id, $product_id ) );
}

代碼進入您的活動子主題(或活動主題)的functions.php文件中 經過測試和工作。


wp_delete_post()一起使用可刪除包含特定產品的相關訂單(標識: 246014

// Get all orders containing 246014 product ID for the current user 
$orders_ids = get_completed_orders_for_user_from_product_id( 246014 );

// Checking that, the orders IDs array is not empty
if( count($orders_ids) > 0 ) {

    // Loop through orders IDs
    foreach ( $orders_ids as $order_id ) {
        // Delete order post data 
        wp_delete_post( $order_id, true );
    }

    // Add the order(s) ID(s) in user meta (example)
    update_user_meta( get_current_user_id(), 'item_246014', implode( ',', $orders_ids ) );
}

相關主題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM