我正在嘗試向我的Woocommerce套件添加新的送貨方式。以編程方式向Woocommerce添加新的送貨方式
基本上我試圖根據用戶角色對訂單應用兩種不同的運費。我使用統一費率作爲其中之一,但需要定製一個。
我試過the shipping api來創建一個新的類,但似乎沒有出現。
<?php namespace MySite;
use WC_Shipping_Method;
function your_shipping_method_init() {
if (! class_exists('CustomShipping')) {
class CustomShipping extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'your_shipping_method'; // Id for your shipping method. Should be uunique.
$this->method_title = __('Your Shipping Method'); // Title shown in admin
$this->method_description = __('Description of your shipping method'); // Description shown in admin
$this->enabled = "yes"; // This can be added as an setting but for this example its forced enabled
$this->title = "My Shipping Method"; // This can be added as an setting but for this example its forced.
$this->init();
}
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* calculate_shipping function.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping($package) {
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => '10.99',
'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate($rate);
}
}
}
add_action('woocommerce_shipping_init', 'your_shipping_method_init');
function add_your_shipping_method($methods) {
$methods[] = 'CustomShipping';
return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_your_shipping_method');
}
我使用Composer來加載我的類。
難道我不應該看到Woocommerce Shipping設置中的新選項嗎?任何指導讚賞。
另一種方法是攔截會話數據,然後在那裏更改運費和稅金。但這似乎並不奏效。我在哪裏可以找到有關運送信息來源的更多數據;何時何地被叫?
啊,是的,我的行動是嵌套的。 @doublesharp我已經實現了你的代碼,看起來好像'your_shipping_method_init'從來沒有被調用過。死亡和傾倒在裏面什麼都沒有做。我的'add_action'和'add_filter'調用不應該在這個文件裏面嗎? – Tuesdave
你把這些代碼放在哪裏?唯一的區別是我添加了一個頭文件,使其成爲一個插件,然後啓用它,否則它在我的測試網站上正常工作。你也可以把它放入'mu-plugins'中。 – doublesharp
我使用插件頭更新了示例代碼。創建一個名爲'/ wp-content/plugins/my-shipping /'的文件夾並將文件放入其中,然後在插件中啓用「WooCommerce Your Shipping Method」,它應顯示在WooCommerce設置中。 – doublesharp