在自定义 php 文件中使用 Woocommerce 函数

Use Woocommerce functions in custom php files

我是 PHP 编程的初学者。我想创建一个 PHP 文件,其中来自预定义顺序(在我的例子中是 108)的 order_status 被更改为已完成。

因此我需要 woocommerce 函数 get_order($ID)update_status 但我不知道如何在我的 PHP 中使用它们。我希望你能理解我的问题。从 Java 我可以想象我需要从 class 或类似的东西中获取一个实例?

这是我目前的代码:

<?php $ord = new WC_Order(108); $ord->update_status('completed'); ?>

当我打开页面时收到以下错误:

Fatal error: Uncaught Error: Class 'WC_Order' not found (...)

一般来说 Wordpress/WooCommerce 您将包含您的函数代码:

  • 在您的活动子主题(或活动主题)中function.php文件
  • 在插件中…

您还可以启用一些代码:

Now to execute that function, you will need an event that will execute your function.

(Wordpress) Woocommerce 中有很多 action hooks 会在某些特定事件上触发,您可以使用这些事件来执行您的功能。在这种情况下你的函数将被挂钩 (准备好在特定事件上执行).

如果您想更改特定订单的状态,最好在后台的相关订单编辑页面中进行。

例子:
例如,当客户在 order-received 端点(谢谢页面)结帐后提交订单时,您可以更改订单状态:

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order');
function custom_woocommerce_auto_complete_order( $order_id ) {
    if ( ! $order_id ) return;

    // Get an instance of the WC_Order object
    $order = wc_get_order( $order_id );
    // Change order status to "completed"
    $order->update_status( 'completed' );
}

此代码为官方代码片段:Automatically Complete Orders.

这是一个很好的例子,向您展示了事情是如何工作的……所以在您的情况下,您在这里使用 WC_Order class 方法,例如 update_status().

现在有了这个代码库,您可以像在这个答案中那样优化行为:


相关订单: