WooCommerce Extending WC_Shipping_Method error: Class 'WC_Shipping_Method' not found

a 夏天 提交于 2019-12-14 02:55:35

问题


The title explains it pretty well. I'm trying to add a new shipping method (cost-based shipping) by extending the class. Here is the plugin body (The rest is in comments and contains the plugin info):

class WC_Cost_Based extends WC_Shipping_Method {
    function __construct() {
        $this->id = 'cost-based';
        $this->method_title = __('Cost-Based', 'woocommerce');
    }

    function calculate_shipping() {
        $rate = array(
            'id' => $this->id,
            'label' => $this->title,
            'cost' => '10.99',
            'calc_tax' => 'per_item'
            );
    // Register the rate
        $this->add_rate( $rate );
    }

}

function add_cost_based_method( $methods ) {
    $methods[] = 'WC_Cost_Based';
    return $methods;
}

add_filter('woocommerce_shipping_methods', 'add_cost_based_method');

The file is saved in .../wp-content/cost-based

Any idea why this error is popping up?


回答1:


I just had the same problem while trying to follow the woocommerce instruction/tutorial. It seems they have left a couple of things out.

Firstly, to solve your question, I found I needed to included the woocommerce.php at the top of my plugin class. This will give the new shipping class access to the WC_Shipping_Method that it needs to extend. There may be a more elegant way of just included the dependant classes only. For me include looks like this:

 include ('/woocommerce/woocommerce.php');

Secondly, I found I also had to set a minimum of two more attributes in the __construct() method. They were:

 $this->title = "YOUR TITLE";  // Displays on the main shipping page
 $this->enabled = true;

Thirdly, I also needed (at a minimum):

function is_available( $package ) {
    if ( $this->enabled == "no" ) return false;
    return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', true );
}

Hope it helps!

Simon




回答2:


navigate to - https://github.com/woocommerce/woocommerce/blob/master/includes/abstracts/abstract-wc-shipping-method.php

copy everything in the php file and replace in the file -abstract-wc-shipping-method.php found in- wp-content/plugins/woocommerce/includes/abstracts/



来源:https://stackoverflow.com/questions/14972184/woocommerce-extending-wc-shipping-method-error-class-wc-shipping-method-not-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!