skip to Main Content

I just created a file called custom_functions.php inside of my current active child theme, and when I try to add a product to the cart with this simple line of code, I get an error:

Code:

<?php
    WC()->cart->add_to_cart( 204 );
    //wc()->cart->add_to_cart( 204 );
?>

Error:

 Fatal error: Uncaught Error: Call to undefined function WC() in /homepages/11/d870651981/htdocs/clickandbuilds/XXXXXXX/wp-content/themes/motors-child/custom_functions.php:2 Stack trace: #0 {main} thrown in /homepages/11/d870651981/htdocs/clickandbuilds/XXXXXXX/wp-content/themes/motors-child/custom_functions.php on line 2

I have been reading on Internet that you don’t need to import anything else, just use WC().

I’m executing that code from functions.php file using jQuery AJAX.

What am I doing wrong?

2

Answers


  1. require('../../../../../../wp-load.php');
    global $woocommerce;
    $woocommerce->cart->add_to_cart($product_id);
    
    Login or Signup to reply.
  2. 1.In your functions.php file, add the following line of code to include the custom_functions.php file:

    // functions.php (child theme)
    include_once( get_stylesheet_directory() . '/custom_functions.php' );
    

    2.In your custom_functions.php file, you can use the ‘woocommerce_loaded’ action hook to ensure that WooCommerce is loaded before your code runs:

    // custom_functions.php (inside your child theme)
    add_action( 'woocommerce_loaded', 'custom_add_to_cart' );
    function custom_add_to_cart() {
        WC()->cart->add_to_cart( 204 );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search