WooCommerce Javascpt或PHP 添加购物车功能 图文教程

前篇老季写了WordPress 商城开发 WooCommerce 插件创建自定义产品类型Product_type 并在前端页面循环中隐藏,本文我们将记录一下,如何使用PHP或Javascript功能来实现添加到购物车功能。

Javascript

<script type="text/javascript">

	function jwc_add_to_cart( product_id ) {
		if ( 'undefined' === typeof wc_add_to_cart_params ) {
			// The add to cart params are not present.
			return false;
		}

		var data = {
			product_id: product_id,
			quantity: 1,
		};

		jQuery.post( wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ), data, function( response ) {
			if ( ! response ) {
				return;
			}

			// This redirects the user to the product url if for example options are needed ( in a variable product ).
			// You can remove this if it's not the case.
			if ( response.error && response.product_url ) {
				window.location = response.product_url;
				return;
			}

			// Remove this if you never want this action redirect.
			if ( wc_add_to_cart_params.cart_redirect_after_add === 'yes' ) {
				window.location = wc_add_to_cart_params.cart_url;
				return;
			}

			// This is important so your theme gets a chance to update the cart quantity for example, but can be removed if not needed.
			jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] );
		});
	}

</script>

PHP

WC()->cart->add_to_cart( $product_id, $quantity );

腾讯云限时秒杀【点击购买】

搬瓦工,CN2高速线路,1GB带宽,电信联通优化KVM,延迟低,速度快,建站稳定,搬瓦工BandwagonHost VPS优惠码BWH26FXH3HIQ,支持<支付宝> 【点击购买】!

Vultr$3.5日本节点,512M内存/500G流量/1G带宽,电信联通优化,延迟低,速度快【点击购买】!

阿里云香港、新加坡VPS/1核/1G/25G SSD/1T流量/30M带宽/年付¥288【点击购买】


`微信`扫码 加好友

发表评论

您的电子邮箱地址不会被公开。