• Resolved Imagejaspash

    (@jaspash)


    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 month, 3 weeks ago by Imagejaspash.
    • This topic was modified 1 month, 3 weeks ago by Imagejaspash.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Support ImageSai (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)?

    Plugin Support Imagethelmachido a11n

    (@thelmachido)

    It’s been a while since we heard back from you for this reason we are closing this thread. 

    If WooCommerce has been useful for your store and you appreciate the support you’ve received, we’d truly appreciate it if you could leave us a quick review here: 

     https://wordpress.org/support/plugin/woocommerce/reviews/#new-post

    Feel free to open a new forum topic if you run into any other problem. 

Viewing 2 replies - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.