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.In your functions.php file, add the following line of code to include the custom_functions.php file:
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: