我正在嘗試查詢我的資料庫并將結果傳遞給update_post_meta函式。但是不確定我是否正確地構建了這個,或者我的$order_id使用是否存在問題?
下訂單后,我需要發布元資料來更新當前登錄用戶和當前訂單的查詢結果,因此認為woocommerce_thankyou使用該鉤子是有意義的,但是在完成訂單后不會寫入任何帖子元資料。
add_filter( 'woocommerce_thankyou', 'my_function', 10, 2);
function my_function( $result, $order_id ) {
// Load the global $post
global $woocommerce, $post;
// Get the post ID
$order_id = $post->ID;
// Then you can get the order object
$order = wc_get_order( $order_id );
$user_ID = get_current_user_id();
//SQL
global $wpdb;
return $wpdb->get_var("SELECT SUM(b03_woocommerce_order_itemmeta.meta_value)
FROM b03_woocommerce_order_itemmeta
JOIN b03_woocommerce_order_items ON b03_woocommerce_order_itemmeta.order_item_id = b03_woocommerce_order_items.order_item_id
JOIN b03_posts ON b03_woocommerce_order_items.order_id = b03_posts.ID
JOIN b03_postmeta ON b03_posts.ID = b03_postmeta.post_id
WHERE b03_posts.post_type = 'shop_order'
AND b03_woocommerce_order_itemmeta.meta_key = 'trees_planted'
AND b03_postmeta.meta_value = $user_ID
AND b03_postmeta.meta_key = '_customer_user'
AND b03_posts.ID = $order_id");
update_post_meta( $order_id, 'trees',$wpdb);
}
感謝有關如何最好地處理此問題的任何建議?
uj5u.com熱心網友回復:
您的代碼嘗試包含多個錯誤和錯誤:
woocommerce_thankyou是一個動作鉤子,而不是過濾器鉤子- 僅
$order_id傳遞給回呼函式,$result不適用 - 使用
$wpdb->prefixvsb03_,這使它動態 $wpdb是一個物件- 的使用
global $woocommerce, $post;是多余的
所以你得到:
function action_woocommerce_thankyou( $order_id ) {
// Get $order object
$order = wc_get_order( $order_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// Get user id
$user_id = $order->get_user_id();
// Not a guest
if ( $user_id > 0 ) {
//SQL
global $wpdb;
// The SQL query
$result = $wpdb->get_var( "
SELECT SUM( oim.meta_value )
FROM {$wpdb->prefix}woocommerce_order_itemmeta as oim
JOIN {$wpdb->prefix}woocommerce_order_items as oi ON oim.order_item_id = oi.order_item_id
JOIN {$wpdb->prefix}posts as p ON oi.order_id = p.ID
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'shop_order'
AND oim.meta_key = 'trees_planted'
AND pm.meta_value = '$user_id'
AND pm.meta_key = '_customer_user'
AND p.ID = '$order_id'
" );
// REMOVE THIS, only for testing purposes
$result = 10;
// Add the meta data
$order->update_meta_data( 'trees', $result );
$order->save();
}
}
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );
注意:因為您使用的是自定義 SQL 查詢,其資料/結果在 WooCommerce 中一般/默認不存在,但僅針對您,我已在我的答案中將其替換為固定值 10。調整位置必要的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477023.html
標籤:mysql WordPress woocommerce 钩woocommerce
上一篇:在動態元素上添加一個類
下一篇:未捕獲的ReferenceError:firstFunc未在HTMLButtonElement.onclickWordpressDivi中定義
