我在Wordpress / Woocommerce项目的functions.php
中有一些代码,我尝试根据用户ID和订单ID更新自定义数据库表:
global $wpdb;
$table = $table="wp_thegraffitiwall";
$user = get_current_user_id();
if($user == 0)
exit();
echo "Current User ID is ";
echo $user;
echo "Current Order ID is ";
$wpdb->update($table,$updateStuff,['userid'=>$user]);
// $wpdb->update($table,$updateStuff,['userid'=>$user] AND 'orderid'=>#orderid);
exit("Saved!");
如您所见,我可以检索当前用户ID并使用它,但我在获取当前订单ID时遇到了问题。
我已经在Stackoverflow上搜索过了,并尝试了如下内容:
$order->get_id();
但这是行不通的。
我想将当前的订单ID分配给$order_id,然后在更新函数中使用它,我现在已经在下面注释掉了它。
发布于 2018-08-15 03:32:45
订单ID仅存在于前端(针对当前用户)的订单接收(谢谢)页面和我的帐户>订单视图页面中。因此,如果在主题的function.php文件中使用,那么您的代码就有点不完整,因为它应该在钩子函数中。
现在,您可以尝试其中一个挂钩函数,其中需要添加与$updateStuff
变量相关的必要代码。这两个函数都将在结帐后创建订单时触发。
第一个替代(您可以直接使用$order_id
,因为它是一个参数):
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_update_order', 25, 2 );
function custom_checkout_update_order( $order_id, $data ) {
global $wpdb;
// Get the user ID from the Order
$user_id = get_post_meta( $order_id, '_customer_user', true );
$updateStuff = 'something'; // <=== <=== <=== <=== HERE you add your code
$wpdb->update( 'wp_thegraffitiwall', $updateStuff, array('userid' => $userid) );
}
代码放在活动子主题(或活动主题)的function.php文件中。
或这一个(您可以直接使用$order_id
作为参数)
add_action( 'woocommerce_thankyou', 'custom_thankyou_action', 20, 1 );
function custom_thankyou_action( $order_id ) {
if ( ! $order_id ) return; // Exit
global $wpdb;
// Get the user ID from the Order
$user_id = get_post_meta( $order_id, '_customer_user', true );
$updateStuff = 'something'; // <=== <=== <=== <=== HERE you add your code
$wpdb->update( 'wp_thegraffitiwall', $updateStuff, array('userid' => $userid) );
}
代码放在活动子主题(或活动主题)的function.php文件中。
https://stackoverflow.com/questions/51846798
复制相似问题