WooCommerce - 从单独的 PHP 文件访问“WC_Order”

t0r*_*rxe 4 html javascript php wordpress woocommerce

我正在使用 Javascript 直接从 WooCommerce(通过 Wordpress)中的 functions.php 文件调用 PHP 文件,该文件使用 GitHub 上提供的“PHP XLSXWriter”代码。但是,我无法访问

$order = new WC_Order($order_id);
Run Code Online (Sandbox Code Playgroud)

我可以通过使用直接在 WooCommerce 后面访问此功能吗

 require_once('/wp-content/plugins/woocommerce/includes/class-wc-order.php');
Run Code Online (Sandbox Code Playgroud)

?

这是我正在调用的整个 PHP 代码:

$order_id = $_GET['order']; // pull the order info from the URL 
$order = new WC_Order($order_id); // this crashes this entire function!
echo $order->shipping_city; // this then fails
echo $order->shipping_country; // and this fails too

// this code doesn't then execute...
$filename = "test.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');

$rows = array(
    array('Shipping Service Code',  'Company',  'Consignee Name',   'Address Line 1',   'Address Line 2',   'Address Line 3'),
    array('PPS',                    '-',        '-',                '-',                '-',                '-'),
);

$writer = new XLSXWriter();
$writer->setAuthor('EXAMPLE AUTHOR');

foreach($rows as $row)
$writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();

exit(0);
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

 Fatal error: Class 'WC_Order' not found in C:\Webs\mysite.com\www\wp-admin\dhlgen.php on line 9
Run Code Online (Sandbox Code Playgroud)

另一个想法是,是否可以直接在我的 function.php 文件中调用 PHP 代码。但是,我把它放在一个 meta_box 按钮上,所以当我点击按钮本身时,它只是保存订单而不执行我的 PHP 代码。我认为这可能是因为 XLSXWriter 逻辑需要停止页面才能转储它无法执行的 Excel 电子表格文件,因此它超时并继续仅保存页面。

谢谢你。

Mic*_*oye 5

您应该能够通过包含以下wp-blog-header文件来访问 WordPress 环境(包括 WooCommerce):

require('path/to/wp-blog-header.php');
Run Code Online (Sandbox Code Playgroud)

或者,或者wp-load文件:

require('path/to/wp-load.php');
Run Code Online (Sandbox Code Playgroud)

集成文档| 相关问题