我一直在编写一个 WP 插件,用于计算订单的平方英寸总体积,并通过自定义字段将其发送到 Shipstation:
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
//Debugging function
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}
console_log('$items');
//Custoom field for shipstation
add_filter( 'woocommerce_shipstation_export_custom_field_2', 'shipstation_custom_field_2' );
//Function for processing volume
function shipstation_custom_field_2() {
$cart_prods_in3 = array();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
//GET GET PRODUCT IN3
$prod_in3 = $_product->get_length() *
$_product->get_width() *
$_product->get_height();
$prod_in3 = $prod_m3 * $values['quantity'];
//PUSH RESULT TO ARRAY
array_push($cart_prods_in3, $prod_in3);
}
return $cart_prods_in3; // Key for your custom field
}
console_log('shipstation_custom_field_2');
?>
我通过 SFTP 将其上传到站点文件,它显示在 WP 上,但是当我单击“激活”时,出现 fatal error :
Fatal error: Uncaught Error: Call to a member function get_cart() on null in /nas/content/live/sfmstaging/wp-content/plugins/boxCalc/boxCalc.php:10 Stack trace: #0 /nas/content/live/sfmstaging/wp-admin/includes/plugin.php(2299): include() #1 /nas/content/live/sfmstaging/wp-admin/plugins.php(191): plugin_sandbox_scrape('boxCalc/boxCalc...') #2 {main} thrown in /nas/content/live/sfmstaging/wp-content/plugins/boxCalc/boxCalc.php on line 10
我提取的购物车数据正确吗? Woocommerce 全局有问题吗?
最佳答案
请注意,购物车是实时客户对象,您无法在实际操作中获得它。
现在在ShipStation plugin documentation woocommerce_shipstation_export_custom_field_2
过滤器 Hook 只是返回现有订单自定义字段的元键。
这意味着当客户下订单时,您需要将购物车总量保存为自定义订单元数据。
请尝试以下操作:
// Custom function to get the volume of a product
function get_product_volume( $product ) {
return $product->get_length() * $product->get_width() * $product->get_height();
}
// Save the cart total volume as custom order meta data
add_action('woocommerce_checkout_create_order', 'save_order_total_volume');
function save_order_total_volume( $order ) {
$total_volume = 0; // Initializing
// Loop through order items
foreach( $order->get_items() as $item ){
$item_volume = get_product_volume($item->get_product()) * $item->get_quantity();
// For product variations (if volume is not accessible get the volume of the parent variabl product)
if( ! $item_volume ) {
$total_volume += get_product_volume( wc_get_product( $item->get_product_id() ) ) * $item->get_quantity();
} else {
$total_volume += $item_volume;
}
}
$order->update_meta_data( '_total_volume', $total_volume ); // Save total volume as custom order meta data
}
// Add total volume custom field meta key for export to ship station
add_filter( 'woocommerce_shipstation_export_custom_field_2', 'shipstation_custom_field_2' );
function shipstation_custom_field_2( $custom_field_key ) {
return '_total_volume';
}
代码位于事件子主题(或事件主题)的functions.php 文件或插件文件中。经过测试并有效。
关于php - 将 WooCommerce 订单总量保存为 Shipstation 的自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66200076/