问题描述
我试图覆盖WooCoommerce的ajax添加到购物车功能并添加此简单条件。
YYYY
我从here那里得到了这个主意,只是将其条件添加到其中只是为了进行测试,但没有用。
$base = true;
if($base){
return the default error just to test...
}else{
default functionality ...
}
我想念什么吗?
解决方法
是的,您错过了整个过程。您需要执行的操作是woocommerce_add_to_cart,而不是wp_ajax_woocommerce_add_to_cart
,而您根本不需要执行wp_ajax_nopriv_woocommerce_add_to_cart
。
您应该从source那里获取这个想法,而不是here。它位于woocommerce/includes/class-wc-ajax.php
上。
记下self::get_refreshed_fragments()
,改用WC_AJAX::get_refreshed_fragments()。
总体而言,您的代码应为:
function woocommerce_ajax_add_to_cart() {
ob_start();
// phpcs:disable WordPress.Security.NonceVerification.Missing
if ( !isset( $_POST[ 'product_id' ] ) ) {
return;
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id',absint( $_POST[ 'product_id' ] ) );
$product = wc_get_product( $product_id );
$quantity = empty( $_POST[ 'quantity' ] ) ? 1 : wc_stock_amount( wp_unslash( $_POST[ 'quantity' ] ) );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation',true,$product_id,$quantity );
$product_status = get_post_status( $product_id );
$variation_id = 0;
$variation = array();
if ( $product && 'variation' === $product->get_type() ) {
$variation_id = $product_id;
$product_id = $product->get_parent_id();
$variation = $product->get_variation_attributes();
}
$base = true;
if ( $base ) { /** Your condition here **/
// If there was an error adding to the cart,redirect to the product page to show any errors.
$data = array(
'error' => true,'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error',get_permalink( $product_id ),$product_id ),);
wp_send_json( $data );
} else {
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id,$quantity,$variation_id,$variation ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart',$product_id );
if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
wc_add_to_cart_message( array( $product_id => $quantity ),true );
}
WC_AJAX::get_refreshed_fragments();
} else {
// If there was an error adding to the cart,redirect to the product page to show any errors.
$data = array(
'error' => true,);
wp_send_json( $data );
}
}
// phpcs:enable
}
add_action( 'woocommerce_add_to_cart','woocommerce_ajax_add_to_cart' );
编辑:您可能在已知的issue(也是here)中,由于函数{{ 1}}。
基于this的源,您可以通过添加条件语句来解决该问题,以使woocommerce_add_to_cart
不会引起问题。
我不知道您要达到什么目的,但是根据您的代码,您似乎只是想在将产品添加到购物车之前添加其他条件。
在这种情况下,您可以执行以下操作。
WC()->cart->add_to_cart(...)
OR
WC()->cart->add_to_cart(...)