【问题标题】:WooCommerce AJAX add to cart - simple products onlyWooCommerce AJAX 添加到购物车 - 仅限简单产品
【发布时间】:2021-04-02 14:24:58
【问题描述】:

我已经按照这个如何指导如何将单个产品的 ajax 添加到购物车:https://aceplugins.com/ajax-add-to-cart-button-on-the-product-page-woocommerce/

我的子主题 function.php 文件中有 php,它可以正常工作。

我遇到的问题是我只想在一个简单的产品上使用remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );,以便它可用于其他产品类型。

我尝试将它添加到 ace_ajax_add_to_cart_handler 函数中,如下所示:

function ace_ajax_add_to_cart_handler() {
    WC_Form_Handler::add_to_cart_action();
    WC_AJAX::get_refreshed_fragments();

    remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
} 
add_action( 'wc_ajax_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );
add_action( 'wc_ajax_nopriv_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );

我也尝试过各种带有条件的函数,但没有任何乐趣,例如:

function remove_cart_action(){
    if ( is_product() ) {
    global $product;
    if( $product->is_type( 'simple' ) ){
    // Remove WC Core add to cart handler to prevent double-add
    remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 ); 
    }
    }
}
add_action( 'init', 'remove_cart_action', 20);

任何建议将不胜感激 - 在此先感谢

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    我更新了您的代码,但不确定它是否有效 你可以检查一下!

    function ace_ajax_add_to_cart_handler() {
        WC_Form_Handler::add_to_cart_action();
        WC_AJAX::get_refreshed_fragments();
    
        $product_id = isset( $_REQUEST['add-to-cart'] ) ? intval( wp_unslash( $_REQUEST['add-to-cart'] ) ) : false;
        if ( $product_id ) {
            $product = wc_get_product( $product_id );
            if ( $product->is_type( 'simple' ) ) {
                remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
            }
        }
    } 
    add_action( 'wc_ajax_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );
    add_action( 'wc_ajax_nopriv_ace_add_to_cart', 'ace_ajax_add_to_cart_handler' );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多