Home > Software design >  Woocommerce change basket icon to tick when product in the basket
Woocommerce change basket icon to tick when product in the basket

Time:07-28

I added some code to my Wordpress site to change the basket icon to a tick/check a couple of years ago. It worked perfectly. Recently I was getting a critical error on my site and narrowed it down to this code. I suspect that there have been subsequent changes in Woocomerce.

Fatal error: Uncaught Error: Call to a member function get_cart() on null in /home/modjargo/public_html/wp-content/themes/ModjajiBooks/functions.php:159 Stack trace: #0 /home/modjargo/public_html/wp-content/themes/ModjajiBooks/functions.php(169): change_button_text(237520, '') #1 /home/modjargo/public_html/wp-includes/class-wp-hook.php(307): change_ajax_add_to_cart_button_text('', Object(WC_Product_Simple)) #2 /home/modjargo/public_html/wp-includes/plugin.php(191): WP_Hook->apply_filters('', Array) #3 /home/modjargo/public_html/wp-content/plugins/woocommerce/includes/class-wc-product-simple.php(62): apply_filters('woocommerce_pro...', 'Add to basket', Object(WC_Product_Simple)) #4 /home/modjargo/public_html/wp-content/plugins/woocommerce/templates/loop/add-to-cart.php(32): WC_Product_Simple->add_to_cart_text() #5 /home/modjargo/public_html/wp-content/plugins/woocommerce/includes/wc-core-functions.php(345): include('/home/modjargo/...') #6 /home/modjargo/public_html/wp-content/plugins/woocommerce/in in /home/modjargo/public_html/wp-content/themes/ModjajiBooks/functions.php on line 159 There has been a critical error on this website. Please check your site admin email inbox for instructions.

Could somebody help me to work out what might be wrong with this code? The second line is the one mentioned in the error.

function change_button_text( $product_id, $button_text ) {
    foreach( WC()->cart->get_cart() as $item ) {
        if( $product_id === $item['product_id'] ) {
            return __('N', 'woocommerce');
        }
    }
    return $button_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_ajax_add_to_cart_button_text', 10, 2 );
function change_ajax_add_to_cart_button_text( $button_text, $product ) {
    if ( $product->is_type('simple') ) {
        $button_text = change_button_text( $product->get_id(), $button_text );
    }
    return $button_text;
}

CodePudding user response:

The WC()->cart doesn't exist in admin hence the get_cart() get called on null error. You can add !is_admin() check so it will not execute in admin page.

function change_ajax_add_to_cart_button_text( $button_text, $product ) {
    if ( !is_admin() && $product->is_type('simple') ) {
        $button_text = change_button_text( $product->get_id(), $button_text );
    }
    return $button_text;
}
  • Related