WordPress的 - 在Woocommerce上使用Ajax添加到购物车的按钮简码

问题描述:

我有一个非常奇怪的问题,我正在做的WordPress的自定义生成。我使用钩子在显示产品的自定义页面上覆盖启动器主题的“添加到购物车”按钮。奇怪的是,当我通过添加到购物车按钮来添加数量选项到我的产品上时,原始的Ajax函数就消失了。然后,我实现了另一个功能,将其添加回来(并使我的自定义“查看购物车”按钮的购物车中的购物车号码更新),但虽然它在购物车中有效,但它似乎不适用于我的自定义商店页面。WordPress的 - 在Woocommerce上使用Ajax添加到购物车的按钮简码

我使用这个片段在我的头处理车的内容:

<?php if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) { 

$count = WC()->cart->cart_contents_count; 
?><a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart'); ?>"><?php 
if ($count > 0) { 
    ?> 
    <span class="cart-contents-count"><?php echo esc_html($count); ?></span> 
    <?php 
} 
    ?></a> 

这里是我的孩子为主题的functions.php我的两个功能:

/** 
* Ensure cart contents update when products are added to the cart via AJAX 
*/ 

function my_header_add_to_cart_fragment($fragments) { 

ob_start(); 
$count = WC()->cart->cart_contents_count; 
?><a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart'); ?>"><?php 
if ($count > 0) { 
    ?> 
    <span class="cart-contents-count"><?php echo esc_html($count); ?></span> 
    <?php    
} 
    ?></a><?php 

$fragments['a.cart-contents'] = ob_get_clean(); 

return $fragments; 
} 

add_filter('woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment'); 


/** 
* Add quantity to products in Products Page 
*/ 
add_filter('woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2); 

function quantity_inputs_for_woocommerce_loop_add_to_cart_link($html, $product) { 
if ($product && $product->is_type('simple') && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually()) { 
    $html = '<form action="' . esc_url($product->add_to_cart_url()) . '" class="cart" method="post" enctype="multipart/form-data">'; 
    $html .= woocommerce_quantity_input(array(), $product, false); 
    $html .= '<button type="submit" class="button alt">' . esc_html($product->add_to_cart_text()) . '</button>'; 
    $html .= '</form>'; 
} 
return $html; 
} 

我认为我的第二个函数添加了一个新的Add-to-cart按钮覆盖了最初的Ajax功能,但是我尝试添加此功能的所有操作都不起作用。我不是最好的JS/jQuery,所以可能是我没有正确地实现我的代码。

任何帮助,这将不胜感激。

需要另一个类添加到按钮即add_to_cart_button & ajax_add_to_cart。 希望这会为你做。

+0

谢谢Tristup,但我试图添加类,它不工作。我试过把它们作为过滤器应用到循环中,我也尝试将它们添加为HTML类添加到按钮中...我在这里丢失了什么吗? – user1192309