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

来源: 老季博客
日期: 2022-5-13
作者: 腾讯云/服务器VPS推荐评测/Vultr
阅读数: 53

前篇老季写了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 );

链接到文章: https://jiloc.com/47773.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注