实用的 WordPress ICP 备案许可管理器

WooCommerce 教程:轻松检查产品 ID 是否在购物车中

这是一个故事:我正在和我的一个自由客户合作,如果这样的产品在购物车中,我需要在结帐中显示某些内容 (产品特定的 「条款和条件」) 。

我一直在购物车中寻找产品,通过购物车 「循环」(foreach)(这里例如:如果产品在购物车中以编程方式应用优惠券) 。

但正如我所说,经过一些随机研究,我发现了另一个魔术 WooCommerce 功能:「find_product_in_cart()」 。这意味着在购物车中找到产品不需要做自定义循环或复杂的 PHP … 它是一个 「一个班轮」!

WooCommerce:找到商品 ID 是否在购物车

PHP 代码段:轻松检查产品 ID 是否在购物车中 – WooCommerce



/**
 * @snippet       Check if Product ID is in the Cart - WooCommerce
 * @sourcecode    https://businessbloomer.com/?p=72733
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.1.1
 */

add_action('woocommerce_before_cart', 'bbloomer_find_product_in_cart');

function bbloomer_find_product_in_cart() {

	$product_id = 282;
	$product_cart_id = WC()->cart->generate_cart_id( $product_id );
	$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

	if ( $in_cart ) {

		$notice = 'Product ID ' . $product_id . ' is in the Cart!';
		wc_print_notice( $notice, 'notice' );

	}

}

如何添加此代码?

1 、您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部 (如果是 CSS 代码,请添加到子主题的 style.css 文件底部) 修改之前建议先备份原始文件,若出现错误请先删除此代码。

2 、 WordPress 4.9 后改进了主题编辑器,对于 CSS 代码也可打开网站前台编辑器的 【自定义】,复制代码添加到自定义 css 中。

此代码是否可用?

如需帮助或是您有更好的方案想分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。

文章没看懂?代码不会用?需要帮助您可以

风间 的头像