【问题标题】:Retrieving the current orderid in wordpress from code in functions.php从functions.php中的代码检索wordpress中的当前orderid
【发布时间】:2018-08-14 17:24:52
【问题描述】:

我在 Wordpress / Woocommerce 项目的 functions.php 中有一些代码,我尝试根据 USER ID 和 ORDER 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!");

如您所见,我可以检索当前的 USER ID 并使用它,但我无法获取当前的 ORDER ID。

我在 Stackoverflow 上进行了搜索并尝试了以下操作:

$order->get_id();

但这不起作用。

我想将当前的 ORDER ID 分配给 $order_id,然后在我目前已注释掉的更新函数中使用它。

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce orders


    【解决方案1】:

    订单 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 文件中。

    【讨论】:

    • 谢谢。您的代码示例确实帮助我了解了发生了什么,并且我能够解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 2014-05-01
    • 2018-03-08
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多