• Hello,

    I get a fatal error when using this code in functions.php of my child theme:

    global $product;
    $product_id = $product->get_id();

    if ( $product_id != 2029 ) {

    // do something

    }

    What am I missing here?

    Please, let me know.

    Regards,

    • This topic was modified 1 week, 1 day ago by jaspash.
    • This topic was modified 1 week, 1 day ago by jaspash.
Viewing 1 replies (of 1 total)
  • Plugin Support Sai (woo-hc)

    (@saivutukuru)

    Hi @jaspash,

    This error occurs because the $product object is not always available globally. Code in functions.php runs on every page load, but $product is only set on WooCommerce product pages and only after WooCommerce has initialized it.

    When $product is null, calling $product->get_id() will trigger a fatal error.

    To avoid this, make sure the code only runs in a product context and that $product is a valid WC_Product object. For example:

    if ( is_product() ) {
        $product = wc_get_product( get_the_ID() );
    
        if ( $product && $product->get_id() != 2029 ) {
            // do something
        }
    }

    Alternatively, if you want to use the global:

    if ( is_product() ) {
        global $product;
    
        if ( $product instanceof WC_Product && $product->get_id() != 2029 ) {
            // do something
        }
    }

    Can you confirm where this logic is intended to run (single product page only, or elsewhere)?

Viewing 1 replies (of 1 total)

You must be logged in to reply to this topic.