1

So I have this in my functions file - it defines the products that are not eligible for free shipping. It works everything is fine.

//functions.php
function my_free_shipping( $is_available ) {
global $woocommerce;

// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );

// get cart contents
$cart_items = $woocommerce->cart->get_cart();

// loop through the items looking for one in the ineligible array
foreach ( $cart_items as $key => $item ) {
    if( in_array( $item['product_id'], $product_notfree_ship ) ) {
        return false;
    }
}

// nothing found return the default value
return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available',    'my_free_shipping', 20 );  

All of the product ID's that I have entered into the array $product_notfree_ship are denied free shipping.

Now I want to call those product IDs on the product pages to check and see if they should receive a "Free shipping applies" message or an "Additional shipping charge applies"

so in my theme/woocommerce/single-product/product-image.php (I want it after the main img) file I have

//theme/woocommerce/single-product/template.php
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
// this is commented because it didn't work, 
// global $product_notfree_ship;

if ( is_single($product_notfree_ship) ) {
 echo 'Additional Shipping Charges Apply';
} else {
    echo 'FREE SHIPPING on This Product';
}

Now, this is working, it just feels stupid to have to edit both arrays, in the event that a new product id needs to be added to the "Not-free-shipping-product-array"

So based on the answer here

I thought if called global $product_notfree_ship; before the if the proper code would run, however it did not.

Is this because I am using is_single() ? Is this because its an array and it needs to be called differently?

Any help is appreciated. Thank you.

2 Answers 2

1

It is all fine. You just need to declare variable global first then you can set the value of this and access globally.

function my_free_shipping( $is_available ) {
global $woocommerce, $product_notfree_ship;

// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );

Then again declare it globally when using again in another file

global $product_notfree_ship;

if ( is_single($product_notfree_ship) ) {
 echo 'Additional Shipping Charges Apply';
} else {
    echo 'FREE SHIPPING on This Product';
}

This is how global variable works.

0
0

Declare it as

global $product_notfree_ship

as you are doing, just access it via this

$GLOBALS['product_notfree_ship'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.