Cálculo del costo de envío de WooCommerce en el complemento de método de envío personalizado [duplicate]

4 minutos de lectura

avatar de usuario de michellemyers90
michellemyers90

Estoy tratando de crear un complemento para WooCommerce que calcule los costos de envío según el peso del producto. Sigo recibiendo este error:

Advertencia: la declaración de WC_Your_Shipping_Method::calculate_shipping($package) debe ser compatible con WC_Shipping_Method::calculate_shipping($package = Array) en C:\Users\Michelle\Dropbox\MEDIEINSTITUTET\Utveckling mot e-handel\WooCommerce\WC-kurs\ wp-content\plugins\frakt\frakt.php en la línea 18

Y este es mi complemento completo:

<?php 
/* *
* Plugin Name: Min frakt modul
  Description: Ett plugin som beräknar frakt kostnad beroende på vikten
*/

/**
 * Check if WooCommerce is active
 */

if (!defined('ABSPATH')) {
    exit;
}

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    function your_shipping_method_init() {
        if ( ! class_exists( 'WC_Your_Shipping_Method' ) ) {
            class WC_Your_Shipping_Method extends WC_Shipping_Method {
                /**
                 * Constructor for your shipping class
                 *
                 * @access public
                 * @return void
                 */
                public function __construct() {
                    $this->id                 = 'mitt-plugin-frakt'; // Id for your shipping method. Should be uunique.
                    $this->method_title       = __( 'Min frakt plugin' );  // Title shown in admin
                    $this->method_description = __( 
                    'Frakten skall beräknas på totalvikten av kundvagnen.<br>
                    Listan är följande:<br>
                    < 1kg = 30kr <br>
                    < 5kg = 60kr <br>
                    < 10kg = 100kr <br>
                    < 20kg = 200kr <br>
                    > 20kg = (Vikten * 10)kr' ); // 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();
                }

                /**
                 * Init your settings
                 *
                 * @access public
                 * @return void
                 */
                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 ) {

                   $alla_items = $package['contents'];
                   $total_weight = 0;
                    foreach ($alla_items as $orderline) {
                        $product_weight = $orderline['data']->weight;
                        $total_weight += $product_weight;
                    };

                    if($total_weight < 1) {
                        $cost="30";
                    } elseif($total_weight > 1 && $total_weight < 5) {
                        $cost="60";
                    } elseif($total_weight > 5 && $total_weight < 10) {
                        $cost="100"; 
                    } elseif($total_weight > 10 && $total_weight < 20) {
                        $cost="200"; 
                    } elseif($total_weight > 20) {
                        $cost = ($total_weight * 10);
                    } else {
                        echo 'ingen vikt';
                    }

                    echo $total_weight;

                    $rate = array( 
                        'id' => $this->id,
                        'label' => $this->title,
                        'cost' => $cost,
                        '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['mitt-plugin-frakt'] = 'WC_Your_Shipping_Method';
        return $methods;
    }

    add_filter( 'woocommerce_shipping_methods', 'add_your_shipping_method' );
}

?>

Realmente no puedo encontrar el error … cuando pruebo el código, solo veo “Mici Shipping” pero no hay precio, lo que significa que de alguna manera no lee la declaración if else. ¡Gracias de antemano por tu ayuda!

Su clase WC_Your_Shipping_Method extiende WC_Shipping_Method que ya tiene ese método. Convierte esto:

public function calculate_shipping( $package ) 

Dentro de esto:

public function calculate_shipping( $package = array() )

  • ¡¡Gracias!! ¡Todo funciona ahora! Sin embargo, tengo otro problema si es tan amable: p El complemento funciona, pero SOLO si son productos diferentes, ¿es como si no calculara si tengo una cantidad diferente en el mismo producto? ¿Alguna idea de por qué?

    – michellemyers90

    24 de abril de 2020 a las 11:02


  • Dame un ejemplo. Entonces, ¿tiene, por ejemplo, una bicicleta con la cantidad 1 y una bicicleta con la cantidad 2? ¿Como, el mismo artículo dos veces pero con diferente cantidad?

    -Robert Vlasiu

    24 de abril de 2020 a las 11:10

  • Estoy probando mi complemento con un sitio web de guitarras, por ejemplo: 1 guitarra eléctrica (peso: 2 kg) – 3 guitarras acústicas (cada peso: 1 kg) El peso total debe ser de 5 kg, pero es 3 kg, porque no calcula el kg de guitarra acustica 3 veces, solo una vez

    – michellemyers90

    24 de abril de 2020 a las 11:12

  • ¿Puedes probar y ver si el problema es que tal vez calcula solo las guitarras acústicas? intente con 1 eléctrica (2 kg) y 2 acústicas (1 kg * 2). su peso total debe ser 4. Si el peso total es 3 significa que calcula 1 eléctrico y 1 acústico. Si calcula solo la acústica, debería devolver 2. Podemos trabajar en el problema después de que aclaremos esto.

    -Robert Vlasiu

    24 de abril de 2020 a las 11:21

  • ¿También puede publicar un var_dump de la matriz “paquete”?

    -Robert Vlasiu

    24 de abril de 2020 a las 11:23

¿Ha sido útil esta solución?