WooCommerce cart initialization fix
November 22, 2024 ยท AI Conversations
User
[Thu Nov 07 13:44:11.940716 2024] [proxy_fcgi:error] [pid 2998739] [client 77.95.113.232:0] AH01071: Got error 'PHP message: get_cart was called incorrectly. Get basket should not be called before the wp_loaded action. Backtrace: require_once('wp-load.php'), require_once('wp-config.php'), require_once('wp-settings.php'), do_action('init'), WP_Hook->do_action, WP_Hook->apply_filters,…"
add_filter( 'woocommerce_add_to_cart_fragments', 'pmm_header_add_to_cart_fragment' );
function pmm_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
Assistant
The error occurs because you're trying to access the cart (`$woocommerce->cart`) too early, before the `wp_loaded` action. This happens because WordPress hasn't fully initialized the WooCommerce cart at the time your filter is being applied.
To resolve this, you can safely access the cart using `WC()->cart` (instead of `$woocommerce->cart`) and ensure it's done at the right stage. Replace your code with the following:
add_filter('woocommerce_add_to_cart_fragments', 'pmm_header_add_to_cart_fragment');
function pmm_header_add_to_cart_fragment($fragments) {
// Safely access the WooCommerce cart
if (WC()->cart) {
ob_start();
?>
<a href="<?php echo esc_url(wc_get_cart_url()); ?>" class="et-cart-info">
<span><?php echo sprintf(_n('%d Item', '%d Items', WC()->cart->get_cart_contents_count(), 'woothemes'), WC()->cart->get_cart_contents_count()); ?></span>
</a>
<?php
$fragments['a.et-cart-info'] = ob_get_clean();
}
return $fragments;
}
### Key Fixes:
1. **Use `WC()->cart`**: This is the recommended way to access the cart object in WooCommerce.
2. **Check if `WC()->cart` exists**: This ensures your code runs only when the WooCommerce cart is initialized.
This modification prevents accessing the cart prematurely, eliminating the `get_cart was called incorrectly` error.