Skip to content
Advertisement

How to get Shipping Methods custom additional data in Woocommerce?

From this comment I’ve created custom field “Shipping Method Description” inside shipping methods:

add_action('woocommerce_init', 'shipping_instance_form_fields_filters');

function shipping_instance_form_fields_filters(){
    $shipping_methods = WC()->shipping->get_shipping_methods();
    foreach($shipping_methods as $shipping_method) {
        add_filter('woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'shipping_instance_form_add_extra_fields');
    }
}

function shipping_instance_form_add_extra_fields( $settings ){
    $settings['shipping_method_description'] = [
        'title'       => 'Shipping Method Description',
        'type'        => 'text', 
        'placeholder' => 'shipping',
        'description' => ''
    ];

    return $settings;
}

But I can’t understand how to get this data in front-end inside my custom shipping template(/cart/cart-shipping.php) like:

<?php if ( $available_methods ) : ?>
    <?php foreach ( $available_methods as $method ) : ?>

        <p><?php /* Method Description ??? */ ?></p>

        <p><?= $method->get_label(); ?></p>
        <p><?= $method->cost; ?></p>

    <?php endforeach; ?>
<?php endif; ?>

This comment isn’t clear for me how to get this instance settings.
Can anyone suggest a solution?

Advertisement

Answer

WooCommerce shipping method settings are stored in wp_options table on option_name column as follows (where $methods_id is name (slug) and $instance_id the numerical identifier):

 $option_name = 'woocommerce_' . $methods_id . '_' . $instance_id . '_settings';

To get that shipping method settings (array) you can use WordPress get_option() function like:

<?php 
if ( $available_methods ) {
    foreach ( $available_methods as $rate ) {
        $data = get_option( 'woocommerce_' . $rate->method_id . '_' . $rate->instance_id . '_settings' ); 

        if ( isset($data['shipping_method_description']) ) {
            echo '<p>' . $data['shipping_method_description'] . '</p>';
        }
        echo '<p>' . $rate->label . '</p>';
        echo '<p>' . $rate->cost . '</p>';
    }
} 
?>

Tested and works.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement