WooCommerce - Access 'WC_Order' from a separate PHP File

I'm using Javascript to call a PHP file directly from my functions.php file in WooCommerce (via Wordpress) which is using the 'PHP XLSXWriter' code available on GitHub. However, I'm having trouble accessing

$order = new WC_Order($order_id);

Can I access this function directly behind WooCommerce by perhaps using

 require_once('/wp-content/plugins/woocommerce/includes/class-wc-order.php');

?

Here is my entire PHP code which I'm calling:

$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);

The error I get is:

 Fatal error: Class 'WC_Order' not found in C:\Webs\mysite.com\www\wp-admin\dhlgen.php on line 9

Another idea is if it's possible to just call the PHP code directly in my function.php file. However, I have it on a meta_box button, so when I click on the button itself, it just saves the order and doesn't execute my PHP code. Reason I think that might be is because the XLSXWriter logic needs to stop the page in order the dump the Excel spreadsheet file which it can't do, so it times out and continues just saving the page.

Thank you.

Answers:

Answer

You should be able to access the WordPress environment (including WooCommerce) by including the wp-blog-header file:

require('path/to/wp-blog-header.php');

Or, alternatively the wp-load file:

require('path/to/wp-load.php');

Intergration Docs | Related Question

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.