I'm trying to add a custom message based on the shipping method chosen by the customer. Using this code, I was able to do it. The only problem is that I should replace the text part with a shortcode.
add_action( 'woocommerce_cart_totals_after_shipping', 'ts_shipping_method_custom_notice' );
add_action( 'woocommerce_review_order_after_shipping', 'ts_shipping_method_custom_notice' );
function ts_shipping_method_custom_notice() {
// HERE DEFINE YOUR TARGETED SHIPPING METHOD(S)
$targeted_shipping_methods = array('local_pickup:3'); // Replace with the actual shipping method ID(s)
// Get the chosen shipping methods
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
if ( ! empty( $chosen_methods ) ) {
$chosen_method = reset( $chosen_methods );
// Check if the chosen shipping method is in the targeted list
if ( in_array( $chosen_method, $targeted_shipping_methods ) ) {
echo '<tr class="shipping">
<td colspan="2" style="text-align:center">' . sprintf(
__( "a vit è na briosh", "woocommerce"),
'<strong>al 100%</strong>',
'<strong>' . WC()->customer->get_shipping_postcode() . '</strong>'
) . '</td>
</tr>';
}
}
}
To display a shortcode, you can use WordPress do_shrotcode()
function in the code like:
add_action( 'woocommerce_cart_totals_after_shipping', 'display_shipping_method_custom_notice' );
add_action( 'woocommerce_review_order_after_shipping', 'display_shipping_method_custom_notice' );
function display_shipping_method_custom_notice() {
$targeted_methods = array('local_pickup:3'); // <== Define the desired shipping method ID(s)
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
if ( ! empty($chosen_methods) ) {
// Targeting the chosen shipping method
if ( in_array( reset($chosen_methods), $targeted_methods) ) {
echo '<tr class="shipping"><td colspan="2" style="text-align:center">' .
do_shortcode("[my_shortcode_here]") .
'</td></tr>';
}
}
}