Сделайте новый способ доставки как часть плагина в Woocommerce - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь создать плагин для woocommerce, и мне нужно создать новый способ доставки как часть его. Я нашел этот сайт и следую его инструкциям. Я только что изменил некоторые имена.

Вот мой код:

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    function hGhPishtazShippingMethod(){
        if (!class_exists('hGhPishtazShippingMethodClass')){
            class hGhPishtazShippingMethodClass extends WC_Shipping_Method {
                function __construct(){
                    $this->id = 'hGhPishtazShiping';
                    $this->method_title = __( 'pishtaz post' ) ;
                    $this->method_description = __( 'sending goods with pishtaz post' );

                    // Available country
                    //$this->availability = 'including';
                    //$this->countries = array('US');

                    // Create from and settings
                    $this->init();
                    $this->enabled = isset( $this->settings['enabled'] ) ? $this->settings['enabled'] : 'yes';
                    $this->title = isset ($this->settings['title']) ? $this->settings['title'] : __( 'pishtaz post' );
                }
                // Init your setting
                function init(){
                    $this->init_form_fields();
                    $this->init_settings();
                    add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
                }

                function init_form_fields(){
                    // Our settings
                    $this->form_fields = array (
                        'enabled' => array(
                            'title' => __( 'Enable' , 'woocommerce' ),
                            'type' => 'checkbox',
                            'description' =>__( 'enable pishtaz post' , 'woocommerce' ),
                            'default' => 'yes'
                        ),
                        'title' => array(
                            'title' => __( 'Title' , 'woocommerce' ),
                            'type' => 'text',
                            'description' => __( 'Title to be shown on the site', 'woocommerce' ),
                            'default' => __( 'pishtaz post', 'woocommerce' )
                        )
                    );
                }

                function calculate_shipping ($package){
                    // Our calculation
                }
            }
        }
    }
    add_action( 'woocommerce_shipping_init', 'hGhPishtazShippingMethod' );

    function add_hGhPishtazShippingMethod( $methods ) {
        $methods[] = 'hGhPishtazShippingMethodClass';
        return $methods;
    }
    add_filter( 'woocommerce_shipping_methods', 'add_hGhPishtazShippingMethod' );
}

Теперь в WooCommerce> Настройки> Доставка я вижу название моего метода, но когда я нажимаю на него, я вижу пустую форму с кнопкой «сохранить изменения». Я проверял код несколько раз, но не нашел, что не так.

вторая проблема: Как видите, этот код предназначен для полного плагина. Я хочу сделать это как часть другого плагина. Каков правильный путь для этого?


обновление:

Я нашел ответ для первой проблемы: идентификатор класса не должен включать заглавные буквы.

1 Ответ

0 голосов
/ 05 января 2019

В вашем коде есть некоторые ошибки и ошибки ... Также вам следует избегать прописных букв в именах функций, именах переменных и слагов в php (отличается от Javascript или других языков сценариев).

Попробуйте вместо этого:

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

    add_action( 'woocommerce_shipping_init', 'exec_pishtaz_shipping_method' );
    function exec_pishtaz_shipping_method(){

        if ( ! class_exists('WC_Shipping_Method_Pishtaz_Post') ) {
            class WC_Shipping_Method_Pishtaz_Post extends WC_Shipping_Method {

                public function __construct( $instance_id = 0 ){
                    $this->id = 'pishtaz';
                    $this->domain = 'pishtaz_post';
                    $this->instance_id = absint( $instance_id );
                    $this->method_title = __( 'Pishtaz post', $this->domain ) ;
                    $this->method_description = sprintf( __( 'sending goods with %s', $this->domain ), $this->method_title );

                    $this->supports = array(
                        'shipping-zones',
                        'instance-settings',
                        'instance-settings-modal',
                    );

                    //available country
                    //$this->availability = 'including';
                    //$this->countries = array('US');


                    //create from and settings
                    $this->init();
                }

                //init your setting
                public function init(){
                    $this->init_form_fields();
                    $this->init_settings();
                    $this->enabled = $this->get_option( 'enabled', $this->domain );
                    $this->title   = $this->get_option( 'title', $this->domain );
                    $this->info    = $this->get_option( 'info', $this->domain );
                    add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options') );

                }

                public function init_form_fields(){
                    //our settings
                    $this->form_fields = array (
                        'title' => array(
                            'title'         => __( 'Title' , $this->domain ),
                            'type'          => 'text',
                            'description'   => __( 'Title to be shown on the site', $this->domain ),
                            'desc_tip'      => true,
                            'default'       => __( 'pishtaz post', $this->domain )
                        ),
                        'cost' => array(
                            'type'          => 'text',
                            'title'         => __( 'Cost', $this->domain ),
                            'description'   => __( 'Enter a cost', $this->domain ),
                            'desc_tip'      => true,
                            'default'       => '',
                        ),
                    );
                }

                public function calculate_shipping ( $packages = array() ){
                    $rate = array(
                        'id'       => $this->id,
                        'label'    => $this->title,
                        'cost'     => '0',
                        'calc_tax' => 'per_item'
                    );

                    $this->add_rate( $rate );
                }
            }
        }
    }

    add_filter( 'woocommerce_shipping_methods', 'add_pishtaz_shipping_method' );
    function add_pishtaz_shipping_method( $methods ) {
        $methods['pishtaz'] = 'WC_Shipping_Method_Pishtaz_Post';
        return $methods;
    }
}

Код помещается в файл function.php вашей активной дочерней темы (или темы) или также в любой файл плагина. Проверено и работает.

Чтобы сделать этот код частью другого плагина: Добавьте этот код в отдельный php-файл, который вы включите, используя следующее в своем основном файле плагина:

include_once( 'subfolder/the-php-file-name.php' );

* (где вы замените subfolder на правильное имя подпапки (если оно существует) и the-php-file-name.php на реальное имя файла php) *

Похожие: Создать новый способ доставки в woocommerce 3

...