skip to Main Content

I´ve created a new free shipping method in woocommerce using the following php code:

if ( ! defined( 'WPINC' ) ) {
 
    die;
 
}
 
/*
 * Check if WooCommerce is active
 */
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

function enviogratuitopeninsula_shipping_init() {
    if ( ! class_exists( 'Imp_WC_Shipping_Free_Local_Pickup' ) ) {

        class Imp_WC_Pickup_Free_Shipping_Method extends WC_Shipping_Method {
            /**
             * Constructor.
             *
             * @param int $instance_id
             */
            public function __construct( $instance_id = 0 ) {
                $this->id           = 'imp_enviopeninsulagratuito_method';
                $this->instance_id  = absint( $instance_id );
                $this->method_title = __( "Envio gratuito para la peninsula", 'imp' );
                $this->supports     = array(
                    'shipping-zones',
                    'instance-settings',
                    'instance-settings-modal',
                );
                $this->init();
            }

            /**
             * Initialize custom shiping method.
             */
            public function init() {

                // Load the settings.
                $this->init_form_fields();
                $this->init_settings();

                // Define user set variables
                $this->title = $this->get_option( 'title' );

                // Actions
                add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
            }

            function init_form_fields() {

                 $this->init_settings();
                $this->form_fields = array(

            'enabled'      => array(
                'title'   => __( 'Activar/Desactivar', 'woocommerce' ),
                'type'    => 'checkbox',
                'label'   => __( 'Una vez desactivado, este método heredado dejará de estar disponible.', 'woocommerce' ),
                'default' => 'no',
            ),
            'title'        => array(
                'title'       => __( 'Titulo', 'woocommerce' ),
                'type'        => 'text',
                'description' => __( 'Esto controla el título que el usuario ve durante el pago.', 'woocommerce' ),
                'default'     => __( 'Envío gratuito', 'woocommerce' ),
                'desc_tip'    => true,
            ),
            'availability' => array(
                'title'   => __( 'Disponibilidad de los métodos', 'woocommerce' ),
                'type'    => 'select',
                'default' => 'all',
                'class'   => 'availability wc-enhanced-select',
                'options' => array(
                    'all'      => __( 'All allowed countries', 'woocommerce' ),
                    'specific' => __( 'Specific Countries', 'woocommerce' ),
                ),
            ),
            'countries'    => array(
                'title'             => __( 'Países específicos', 'woocommerce' ),
                'type'              => 'multiselect',
                'class'             => 'wc-enhanced-select',
                'css'               => 'width: 400px;',
                'default'           => '',
                'options'           => WC()->countries->get_shipping_countries(),
                'custom_attributes' => array(
                    'data-placeholder' => __( 'Seleccione algunos países', 'woocommerce' ),
                ),
            ),
            'requires'     => array(
                'title'   => __( 'El envío gratuito requiere...', 'woocommerce' ),
                'type'    => 'select',
                'class'   => 'wc-enhanced-select',
                'default' => '',
                'options' => array(
                    ''           => __( 'N/D', 'woocommerce' ),
                    'coupon'     => __( 'Un cupón de envío gratuito válido', 'woocommerce' ),
                    'min_amount' => __( 'Un importe mínimo de pedido', 'woocommerce' ),
                    'either'     => __( 'Un importe mínimo de pedido O un cupón', 'woocommerce' ),
                    'both'       => __( 'Un importe mínimo de pedido Y un cupón', 'woocommerce' ),
                ),
            ),
            'min_amount'   => array(
                'title'       => __( 'Importe mínimo del pedido', 'woocommerce' ),
                'type'        => 'price',
                'placeholder' => wc_format_localized_price( 0 ),
                'description' => __( 'Los usuarios tendrán que gastar esta cantidad para obtener el envío gratuito (si está activado arriba).', 'woocommerce' ),
                'default'     => '0',
                'desc_tip'    => true,
            ),
         );

            }

            /**
             * calculate_shipping function.
             *
             * @access public
             *
             * @param mixed $package
             *
             * @return void
             */

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

                // Register the rate
                $this->add_rate( $rate );
            }
        }
    }
}
add_action( 'woocommerce_shipping_init', 'enviogratuitopeninsula_shipping_init' );

function envioapeninsulagratuito_shipping_method( $methods ) {
    $methods['imp_enviopeninsulagratuito_method'] = 'Imp_WC_Pickup_Free_Shipping_Method';

    return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'envioapeninsulagratuito_shipping_method' );
}

In the following picture you can see the result:

enter image description here

The problem occurs when clicking "save changes", it doesn´t save them. Is there a way to create a different free shipping method appart from the default one of woocommerce?? I mean, same fields and same option but different ID.

2

Answers


  1. Chosen as BEST ANSWER

    I´ve added the following code to the previous one:

    ´´´´

         /**
             * Process and redirect if disabled.
             */
            public function process_admin_options() {
                parent::process_admin_options();
    
                if ( 'no' === $this->settings['enabled'] ) {
                    wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=shipping&section=options' ) );
                    exit;
                }
            }
    

    ´´´´ Now it seems to be trying to save the the configuration fields (minimum amount for activating the free shipping, countries...), but the saving doesn´t finish...

    Bucle when trying to save


  2. Use $this->instance_form_fields instead of $this->form_fields in the init_form_fields() method.

    function init_form_fields() {
    
        $this->init_settings();
        $this->instance_form_fields = array(
    
            'enabled'      => array(
                'title'   => __( 'Activar/Desactivar', 'woocommerce' ),
                'type'    => 'checkbox',
                'label'   => __( 'Una vez desactivado, este método heredado dejará de estar disponible.', 'woocommerce' ),
                'default' => 'no',
            ),
            'title'        => array(
                'title'       => __( 'Titulo', 'woocommerce' ),
                'type'        => 'text',
                'description' => __( 'Esto controla el título que el usuario ve durante el pago.', 'woocommerce' ),
                'default'     => __( 'Envío gratuito', 'woocommerce' ),
                'desc_tip'    => true,
            ),
            'availability' => array(
                'title'   => __( 'Disponibilidad de los métodos', 'woocommerce' ),
                'type'    => 'select',
                'default' => 'all',
                'class'   => 'availability wc-enhanced-select',
                'options' => array(
                    'all'      => __( 'All allowed countries', 'woocommerce' ),
                    'specific' => __( 'Specific Countries', 'woocommerce' ),
                ),
            ),
            'countries'    => array(
                'title'             => __( 'Países específicos', 'woocommerce' ),
                'type'              => 'multiselect',
                'class'             => 'wc-enhanced-select',
                'css'               => 'width: 400px;',
                'default'           => '',
                'options'           => WC()->countries->get_shipping_countries(),
                'custom_attributes' => array(
                    'data-placeholder' => __( 'Seleccione algunos países', 'woocommerce' ),
                ),
            ),
            'requires'     => array(
                'title'   => __( 'El envío gratuito requiere...', 'woocommerce' ),
                'type'    => 'select',
                'class'   => 'wc-enhanced-select',
                'default' => '',
                'options' => array(
                    ''           => __( 'N/D', 'woocommerce' ),
                    'coupon'     => __( 'Un cupón de envío gratuito válido', 'woocommerce' ),
                    'min_amount' => __( 'Un importe mínimo de pedido', 'woocommerce' ),
                    'either'     => __( 'Un importe mínimo de pedido O un cupón', 'woocommerce' ),
                    'both'       => __( 'Un importe mínimo de pedido Y un cupón', 'woocommerce' ),
                ),
            ),
            'min_amount'   => array(
                'title'       => __( 'Importe mínimo del pedido', 'woocommerce' ),
                'type'        => 'price',
                'placeholder' => wc_format_localized_price( 0 ),
                'description' => __( 'Los usuarios tendrán que gastar esta cantidad para obtener el envío gratuito (si está activado arriba).', 'woocommerce' ),
                'default'     => '0',
                'desc_tip'    => true,
            ),
        );
    
    }
    

    For obtaining these values use the $this->get_option() method like you did in the init() method:

        // Define user set variables
        $this->title = $this->get_option( 'title' );
    

    In some cases you may need the get_instance_from_fields() method but I have a working solution without it:

        /**
         * Get setting form fields for instances of this shipping method within zones.
         *
         * @return array
         */
        public function get_instance_form_fields() {
            return parent::get_instance_form_fields();
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search