在自定义 php 文件中使用 Woocommerce 函数 [英] Use Woocommerce functions in custom php files

查看:88
本文介绍了在自定义 php 文件中使用 Woocommerce 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全是 PHP 编程的初学者.我想创建一个 PHP 文件,其中来自预定义订单(在我的情况下为 108)的 order_status 被更改为已完成.

I am a total beginner in programming with PHP. I wanted to create a PHP file in which the order_status from a predefined order (in my case 108) gets changed to completed.

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

Therefore I need the woocommerce functions get_order($ID) and update_status but I do not know how to use them in my PHP. I hope you understand my problem. From Java I could imagine that I need to get an instance from a class or something like that?

这是我到目前为止的代码:

Here is the code I have so far:

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

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

When I open the page I receive the following error:

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

推荐答案

通常在 Wordpress/WooCommerce 上,您将包含您的函数代码:

In general on Wordpress/WooCommerce you will include your functions code:

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

您还可以在以下位置启用一些代码:

You can also enable some code in:

现在要执行该函数,您将需要一个将执行您的函数的事件.

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

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

In (Wordpress) Woocommerce there is a lot of action hooks that are triggered on some specific events that you can use to execute your function. In this case your function will be hooked (ready to be executed on a specific event).

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

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

An example:
For example you can change the order status when a customer has submit his order after checkout on order-received end point (thankyou page):

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' );
}

此代码是官方代码片段:自动完成订单.

This code is an official code snippet: Automatically Complete Orders.

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

It is a good example that shows you how things can work… So in your case you are using here WC_Order class methods like update_status().

现在有了这个代码库,你可以像这个答案一样改进行为:
WooCommerce:自动完成付费订单(取决于付款)方法)

Now with this code base, you can refine the behaviors like in this answer:
WooCommerce: Auto complete paid Orders (depending on Payment methods)

与订单相关:如何获取 WooCommerce 订单详情

这篇关于在自定义 php 文件中使用 Woocommerce 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆