skip to Main Content

In my wordpress website I getting below error

Fatal error: Call to a member function get_id() on boolean in /home/customer/www/ae.testing.com/public_html/wp-content/themes/movedo-child/functions.php on line 33

Previously working fine . but now what exact issue i am not getting. if any one have idea then let me know

function.php as follows:

<?php
function movedo_child_theme_setup() {
}
add_action( 'after_setup_theme', 'movedo_child_theme_setup' );


function display_price_in_variation_option_name( $term ) {
   echo  $product = wc_get_product();
    $id = $product->get_id();
    if ( empty( $term ) || empty( $id ) ) {
        return $term;
    }
    if ( $product->is_type( 'variable' ) ) {
        $product_variations = $product->get_available_variations();
    } else {
        return $term;
    }

    foreach($product_variations as $variation){
        if(count($variation['attributes']) > 1){
            return $term;
        }
        foreach($variation['attributes'] as $key => $slug){
            if("attribute_" == mb_substr( $key, 0, 10 )){
                $taxonomy = mb_substr( $key, 10 ) ;
                $attribute = get_term_by('slug', $slug, $taxonomy);
                if($attribute->name == $term){
                    $term .= " (" . wp_kses( wc_price($variation['display_price']), array()) . ")";
                }
            }
        }
    }
    
    return $term;

}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

On line "$id = $product->get_id();" I m getting this error.

2

Answers


  1. The issue seems quite simple, you are hooking into ‘after_setup_theme’ which is fired for every single wordpress request. In this context you are supposing you always have a product in the main query context which is not always true.

    To simply shut the error wrap $id = $product->get_id(); into an if like this:

    if(!empty($product)){    
        $id = $product->get_id();
    }
    ...
    

    But to really make it bullet proof you should ask yourself when you really want to look into wc_get_product to get the current product. I’m assuming you may want that only on the product detail page.
    Since you are hooking into ‘after_setup_theme’ conditional tags can be used.

    Change your code to bail out as soon as it is not executed in the right page doing something like this:

    function display_price_in_variation_option_name( $term ) {
        if (!is_product()){
            return;
        }
        echo  $product = wc_get_product();
        $id = $product->get_id();
        ...
    
    Login or Signup to reply.
  2. Wc_get_product is returning false somehow.
    Try

    global $product; //
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search