我正在使用 Javascript 直接从 WooCommerce 中的 functions.php 文件(通过 Wordpress)调用 PHP 文件,该文件使用 GitHub 上提供的“PHP XLSXWriter”代码。但是,我无法访问
$order = new WC_Order($order_id);
我可以通过可能使用直接在 WooCommerce 后面访问此功能吗
require_once('/wp-content/plugins/woocommerce/includes/class-wc-order.php');
?
这是我正在调用的整个 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);
我得到的错误是:
Fatal error: Class 'WC_Order' not found in C:\Webs\mysite.com\www\wp-admin\dhlgen.php on line 9
另一个想法是是否可以直接在我的 function.php 文件中调用 PHP 代码。但是,我将它放在 meta_box 按钮上,因此当我单击按钮本身时,它只会保存订单而不执行我的 PHP 代码。我认为这可能是因为 XLSXWriter 逻辑需要停止页面才能转储它无法执行的 Excel 电子表格文件,因此它会超时并继续保存页面。
谢谢你。
最佳答案
您应该能够通过包含 wp-blog-header
访问 WordPress 环境(包括 WooCommerce)。文件:
require('path/to/wp-blog-header.php');
或者,
wp-load
文件:require('path/to/wp-load.php');
Intergration Docs | Related Question
关于javascript - WooCommerce - 从单独的 PHP 文件访问 'WC_Order',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113813/