利用ajax添加到购物车代码,Woocommerce添加到购物车链接Ajax在其他帖子或页面中启用...

要在自定义添加到购物车按钮中启用ajax,至少有3种方法:

A simple HTML Ajax add to cart link:

Add to cart

Using Woocommerce existing [add_to_cart id='123'] shortcode (与上述用法相同)

xWTDv.png

wABBY.png

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代码:

LdhVs.png

skAyu.png

隐藏Ajax“查看购物车”对于自定义短代码,要隐藏Ajax“查看购物车”行为,可以在返回$ add_to_cart_button之前添加代码;以下内容:$ style ='

$ add_to_cart_button = $ style . $ add_to_cart_button;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值