要在自定义添加到购物车按钮中启用ajax,至少有3种方法:
A simple HTML Ajax add to cart link:
Add to cart
Using Woocommerce existing [add_to_cart id='123'] shortcode (与上述用法相同)
The most customizable: A custom shortcode without price included (可自定义的按钮文本,附加类,数量和许多其他可能性)
if( ! function_exists('custom_ajax_add_to_cart_button') && class_exists('WooCommerce') ) {
function custom_ajax_add_to_cart_button( $atts ) {
// Shortcode attributes
$atts = shortcode_atts( array(
'id' => '0', // Product ID
'qty' => '1', // Product quantity
'text' => '', // Text of the button
'class' => '', // Additional classes
), $atts, 'ajax_add_to_cart' );
if( esc_attr( $atts['id'] ) == 0 ) return; // Exit when no Product ID
if( get_post_type( esc_attr( $atts['id'] ) ) != 'product' ) return; // Exit if not a Product
$product = wc_get_product( esc_attr( $atts['id'] ) );
if ( ! $product ) return; // Exit when if not a valid Product
$classes = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) ).' '.$atts['class'];
$add_to_cart_button = sprintf( '%s',
esc_url( $product->add_to_cart_url() ),
'data-quantity="' . esc_attr( $atts['qty'] ) .'"',
'data-product_id="' . esc_attr( $atts['id'] ) .'"',
'data-product_sku="' . esc_attr( $product->get_sku() ) .'"',
esc_attr( isset( $classes ) ? $classes : 'button' ),
esc_html( empty( esc_attr( $atts['text'] ) ) ? $product->add_to_cart_text() : esc_attr( $atts['text'] ) )
);
return $add_to_cart_button;
}
add_shortcode('ajax_add_to_cart', 'custom_ajax_add_to_cart_button');
}
此代码位于活动子主题(或主题)的function.php文件中 . 经过测试和工作 .
USAGE:
在帖子和页面文本编辑器中:
[ajax_add_to_cart id='123' text='Buy']
在PHP文件或模板中:
echo do_shortcode( "[ajax_add_to_cart id='123' text='Buy']" );
在php页面上插入HTML代码:
隐藏Ajax“查看购物车”对于自定义短代码,要隐藏Ajax“查看购物车”行为,可以在返回$ add_to_cart_button之前添加代码;以下内容:$ style ='
$ add_to_cart_button = $ style . $ add_to_cart_button;