Wordpress - 在Woocommerce上使用Ajax添加到购物车按钮短代码

时间:2017-02-10 09:29:13

标签: php jquery ajax wordpress woocommerce

我在Wordpress中使用自定义构建时遇到了一个非常奇怪的问题。我正在使用挂钩在显示产品的自定义页面上覆盖启动主题的“添加到购物车”按钮。奇怪的是,当我遍历“添加到购物车”按钮以在我的产品上添加数量选项时,原始的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>

以下是我的子主题函数中的两个函数.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;
}

我认为我添加新的“添加到购物车”按钮的第二个功能是覆盖初始的Ajax功能,但我尝试重新添加此功能的所有功能都无效。我不是JS / jQuery中最好的,所以我可能没有正确实现我的代码。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

需要在按钮上添加另一个类,即 add_to_cart_button &amp;的 ajax_add_to_cart 即可。 希望这能为你做到。

相关问题