Sunday, March 13, 2022

[FIXED] WooCommerce compatibility - using get_id() method with older versions in third party plugins

Issue

Does anyone know if it would be possible to add the get_id() method with an older version of WooCommerce in a third party plugin, so it would work with the Google tag manager plugin?

I don't want to update the plugin right now as it would mess up to site.

Anyone know if it's possible?

Thanks


Solution

Yes you can use the PHP function method_exists() on any WooCommerce object like WC_Product or WC_Order objects...

Here is an example with WC_Product object $product:

// WooCommerce retro-compatibility (compact)
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $order->id;

Or you can use version_compare() PHP function too:

// WooCommerce retro-compatibility (2)
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
    // Older than 3.0
    $product_id = $product->id;
} else {
    // 3.0 and above
    $product_id = $product->get_id();
}

and the same in a compact way:

$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $product->id : $product->get_id();

(the $product is an existing and defined WC_Product object…)



Answered By - LoicTheAztec

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.