Sharing data between filters on a snippet (user specific) for Woocommerce

Question

So here’s what I need to do: find out the cheapest shipping method and change the “Free Shipping” method label to “Free Shipping” + “Cheapest method label”. This way the customer will be able to know what is the shipping method used for the free shipping.

First I thought about global variables.. then using the wp_options, but I am not certain if the wp_options are user shared or user specific data.

Would you have any good idea or corrections on the following code, which by the way isn’t working? Thanks!

function wf_default_shipping_method( $method ) {

$the_cheapest_cost = 1000000;


$packages = WC()->shipping()->get_packages()[0]['rates'];

foreach ( array_keys( $packages ) as $key ) {
    if ( ( $packages[$key]->cost > 0 ) && ( $packages[$key]->cost < $the_cheapest_cost ) ) {
      
        $the_cheapest_cost = $packages[$key]->cost;
        $transport_label = $packages[$key]->label;
        
        $method_id = $packages[$key]->id;
    }
}
if(get_option('atransport')){
  update_option('atransport', $transport_label);
}else{
  add_option('atransport', $transport_label);
}

return $method_id;

}
add_filter( ‘woocommerce_shipping_chosen_method’, ‘wf_default_shipping_method’, 10 );

add_filter( ‘woocommerce_package_rates’, ‘change_shipping_methods_label_names’, 20, 2 );
function change_shipping_methods_label_names( $rates, $package ) {

$transport = get_option('atransport');

foreach( $rates as $rate_key => $rate ) {

    if ( __( 'Free Shipping', 'woocommerce' ) == $rate->label ){
      
        $rates[$rate_key]->label = __( 'FreeShipping -' . $transport, 'woocommerce' ); // New label name
    }
  


}

delete_option('atransport');

return $rates;

}

0
RickON 1 month 2021-10-20T10:16:59-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse