Hi,
My theme, Flatsome, as I’d imagine many themes are doing nowadays, add products to cart via ajax. The problem is, in “/includes/abstracts/class-wc-csp-abstract-restriction.php,” you have an “is_admin” check in the function “get_matching_rules_map.” Because the products are being added to cart via ajax, thus using admin-ajax.php, the admin check – starting on line 794 – returns true and the rules are therefore not applied due to the function bailing before the rules map is generated.
I have a suggested fix.
Replace:
// Bail out early and not run if we’re on wp-admin.
if ( is_admin() ) {
return array();
}
With (something like):
// Bail out early and do not run if we’re in wp-admin.
$script_filename = $_SERVER[ ‘SCRIPT_FILENAME’ ] ?? ”;
$script_filename = basename( $script_filename );
if ( wp_doing_ajax() && $script_filename === ‘admin-ajax.php’ ) {
$referer = $_REQUEST[ ‘_wp_http_referer’ ] ?? ( $_SERVER[ ‘HTTP_REFERER’ ] ?? ” );
$referer = wp_unslash( $referer );
$admin_path = admin_url();
$admin_path = basename( $admin_path );
if ( ! $referer || ( stripos( $referer, $admin_path ) > 0 ) ) {
return array();
}
} elseif ( is_admin() ) {
return array();
}
This will essentially determine if the admin ajax request is coming from the frontend and will continue to generate the rule maps. I have tested this on my client’s store, rpmpower.com, and it’s now working as it should be – restricting certain shipping methods depending on the product and shipping class(es) in the cart.
The only other option would be to toggle the add to cart via ajax setting to off in Flatsome, while I’d imagine other themes may not even have such a setting, and if I’m honest, I’d rather not do that anyway.
Thanks for your time and consideration.
Best,
Dave
Open
Last updated: February 12, 2024
Log in to comment on this feature request.
Hiya Dave!
Orhan from Woo.com here. Nice to be connecting and thank you for proactively sharing a suggested fix for the Add to Cart issue you are experiencing with Woo and the Flatsome theme.
A little background on single product page functionality — AJAX Add to Cart buttons in the single product page are not supported by WooCommerce core. WooCommerce only supports AJAX Add to Cart buttons in the Shop/Catalog pages. AJAX Add to Cart buttons in the single product page are added by each theme individually. Therefore, there isn’t a single solution that would automatically work with all AJAX Add to Cart buttons.
Removing the `is_admin` check is not something that we would consider, unfortunately, because then the plugin code would run in admin pages as well and this would have a performance impact on sites.
With that said, if this request gets a lot of votes, we would consider investigating a specific Conditional Shipping and Payments/Flatsome integration that would cover this use-case as well.