WooCommerce操作购物车的动作和过滤器

tech2022-12-24  110

Welcome to the second article in the series on Mastering WooCommerce Actions and Filters. In the previous article, even though it was very basic, we covered handling a customer’s billing and shipping address as well as what happens when a customer registers through WooCommerce and it sends them to a third party website, like Salesforce.

欢迎阅读“掌握WooCommerce动作和过滤器”系列文章中的第二篇文章。 在上一篇文章中 ,尽管这是非常基础的,但我们涵盖了处理客户的账单和送货地址,以及客户通过WooCommerce注册并将其发送到第三方网站(如Salesforce)时发生的情况。

In this second article, we will manipulate the cart in some clever ways with real world scenarios you may encounter while creating your eCommerce website using WooCommerce.

在第二篇文章中,我们将使用在使用WooCommerce创建电子商务网站时可能遇到的真实场景,以一些巧妙的方式来操纵购物车。

以编程方式将产品添加到购物车 (Adding a Product to the Cart Programatically)

Adding a product to the cart programatically only takes one line of code. The only brainstorming you’ll be doing is deciding when or why you’ll want to do it. We’ll talk more about this later in the third part of this article, when we work on our real world scenario.

以编程方式将产品添加到购物车仅需一行代码。 您要做的唯一头脑风暴就是确定何时或为什么要这样做。 当我们在现实世界中工作时,我们将在本文的第三部分中稍后讨论更多。

All it takes to add a product to the cart is the following:

将产品添加到购物车所需的一切如下:

<?php // Takes the Product ID and the Quantity WC()->cart->add_to_cart( 73, 1 );

As a note of caution, make sure you don’t run this on an action that runs on every page, like the template_redirect action or you’ll be adding one of these products to the cart every page load or you reloads. Avoid doing this whenever possible:

请注意,请确保不要在每个页面上都执行的操作(例如template_redirect操作)上运行此操作,否则您将在每次加载页面或重新加载页面时将其中一种产品添加到购物车中。 尽可能避免这样做:

<?php // template_redirect runs once for every page so you'll be // increasing the quantity by one on every page load add_action( 'template_redirect', 'add_random_product' ); function add_random_product() { WC()->cart->add_to_cart( 73, 1 ); }

以编程方式从购物车中移除产品 (Removing a Product from the Cart Programatically)

I’ve seen this question being asked an infinite number of times in various forums and websites with very little answers. Hopefully this will help you the next time you want to remove a product from the cart and again, the only brainstorming you’ll be doing is when or why you would want to remove a product from the cart. The following code will prevent anyone from checking out with a product from your store. I don’t know why you would want to do something like that but it will demonstrate the steps for removing the product from the cart which is not as simple as the previous example when we added the product to the cart.

我已经看到这个问题在各种论坛和网站中被问了无数次,而答案却很少。 希望这将在您下次要从购物车中移除产品时为您提供帮助,并且再次引起您的脑力激荡是何时或为何要从购物车中移除产品。 以下代码将阻止任何人从您的商店中检出产品。 我不知道您为什么要执行类似的操作,但是它将演示从购物车中移除产品的步骤,这不像我们将产品添加到购物车时的上一个示例那样简单。

<?php add_action( 'template_redirect', 'remove_product_from_cart' ); function remove_product_from_cart() { // Run only in the Cart or Checkout Page if( is_cart() || is_checkout() ) { // Set the product ID to remove $prod_to_remove = 56; // Cycle through each product in the cart foreach( WC()->cart->cart_contents as $prod_in_cart ) { // Get the Variation or Product ID $prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id']; // Check to see if IDs match if( $prod_to_remove == $prod_id ) { // Get it's unique ID within the Cart $prod_unique_id = WC()->cart->generate_cart_id( $prod_id ); // Remove it from the cart by un-setting it unset( WC()->cart->cart_contents[$prod_unique_id] ); } } } }

以编程方式清空购物车 (Emptying the Cart Programatically)

To better illustrate how to empty the cart programatically, let’s add a button to the cart which would allow customers to click on it and clear their cart.

为了更好地说明如何以编程方式清空购物车,让我们在购物车中添加一个按钮,使客户可以单击它并清除他们的购物车。

Let’s use the woocommerce_proceed_to_checkout action an echo our very own ‘Submit’ button which will clear the cart for the current customer.

让我们使用woocommerce_proceed_to_checkout操作回显我们自己的“提交”按钮,该按钮将为当前客户清除购物车。

<?php add_action( 'woocommerce_proceed_to_checkout', 'insert_empty_cart_button' ); function insert_empty_cart_button() { // Echo our Empty Cart button echo '<input type="submit" class="button" name="empty_cart" value="Empty Cart" />'; }

The next step is to listen for the button to be clicked so that when it is clicked, we clear the cart. For that, we are going to hook into the template_redirect action.

下一步是侦听要单击的按钮,以便在单击该按钮时,我们清除购物车。 为此,我们将挂接到template_redirect动作。

<?php // Let's wait for the button to be clicked on add_action( 'template_redirect', 'empty_cart_button_handler' ); function empty_cart_button_handler() { if( isset( $_POST['empty_cart'] ) && $_SERVER['REQUEST_METHOD'] == "POST" ) { WC()->cart->empty_cart( true ); } }

You’ll notice now that after pressing the button, the cart-empty.php is displayed instead of the regular template.

您现在会注意到,按下按钮后,将显示cart-empty.php而不是常规模板。

Now that we’ve established how to add or remove a product from the cart, even emptying the cart completely, let’s move on to building our real world scenario where knowing this kind of stuff makes a big difference.

现在,我们已经确定了如何在购物车中添加产品或从购物车中删除产品,甚至完全清空购物车,让我们继续构建真实的场景,在这种情况下,了解这种东西会带来很大的不同。

奖励产品 (Incentive Products)

In our real world scenario, we’re going to put all of this to work by building a system where you could give away a product as an incentive to all of your customers. Well, not exactly to all of your customers, just those who qualify based on a specific requirement.

在现实世界中,我们将通过构建一个系统来使所有这些功能发挥作用,在该系统中您可以赠送产品来激励所有客户。 嗯,不完全对您所有的客户来说,只是那些根据特定要求合格的客户。

问题 (The Problem)

We need to be able to give out a product of your choice as an incentive to your customers.

我们需要能够提供您选择的产品来激励您的客户。

解决方案 (The Solution)

Build a system which will allow you to give away your incentive product based on the following:

建立一个系统,该系统将使您能够根据以下内容赠送奖励产品:

Having a specific product in the cart

购物车中有特定产品

Having a minimum total amount for your order

订单总金额最少

Having a minimum weight in your cart

购物车中的重量最少

Having a product from a specific category

有特定类别的产品

Because we are going to be building this the right way, not only will you be able to give away the product for customer qualifying to one of these criteria, but you’ll also be able to mix these up and really narrow down who gets the product and who doesn’t.

因为我们将以正确的方式进行构建,所以您不仅可以为符合以下条件之一的客户赠送产品,而且还可以将这些条件混合使用,并真正缩小获得这些条件的范围。产品,谁没有。

Not only will you be able to offer your customers the incentive product by qualifying to one of those criteria, you’ll have the power to combine them. In order words, for example, you’ll be able to test for someone having at least $100 total in their cart and a product from the ‘Clothing’ category.

通过符合这些条件之一,您不仅可以为客户提供奖励产品,而且还可以将它们组合在一起。 举例来说,您可以测试购物车中的商品总价至少为$ 100的用户以及“服装”类别中的商品。

Let’s take a quick look at the functions we’ll be writing in a minute and what each does in our problem/solution scenario.

让我们快速看一下我们即将编写的功能,以及每个功能在问题/解决方案中的作用。

get_id_from_product( $product, $check_variations = true ) – Gets the product ID and returns it. Takes variation IDs into account so we check for these before checking for the actual Product ID.

get_id_from_product( $product, $check_variations = true ) –获取产品ID并将其返回。 考虑到变体ID,因此我们在检查实际产品ID之前先进行检查。

qualifies_basedon_specific_product( $product_required ) – Checks whether or not a customer qualifies for the incentive by having the specified product ID as one of the items in the cart.

qualifies_basedon_specific_product( $product_required ) –检查客户是否具有指定的商品ID作为购物车中的商品之一,从而有资格获得奖励。

qualifies_basedon_weight( $weight_required ) – Checks whether or not a customer qualifies for the incentive by having a minimum weight in the cart.

qualifies_basedon_weight( $weight_required ) –检查客户是否通过在购物车中放置最小的重量来获得奖励。

qualifies_basedon_cart_total( $total_required ) – Checks whether or not the customer qualifies for the incentive by having a minimum total amount before taxes are calculated.

qualifies_basedon_cart_total( $total_required ) –检查客户是否在计算税额之前拥有最少的总金额来符合激励条件。

qualifies_basedon_product_category( $category ) – Checks whether or not the customer qualifies for the incentive by having a product from a certain category in the cart.

qualifies_basedon_product_category( $category ) –检查客户是否通过在购物车中购买某个类别的产品来获得奖励的资格。

add_incentive_to_cart( $product_id ) – Adds the incentive product to the cart if the customer qualified for it

add_incentive_to_cart( $product_id ) –如果客户有资格将奖励产品添加到购物车中

remove_incentive_from_cart( $product_id ) – Removes the incentive product to the cart if the customer failed to qualify for the product.

remove_incentive_from_cart( $product_id ) –如果客户未能获得奖励产品的资格,则将其从购物车中移除。

qualifies_for_incentive() – This is where the magic will happen because it will have the rules that need to be matched in order for the customer to qualify for the incentive. This function will handle the logic for our incentive program.

qualifies_for_incentive() –这是发生魔术的地方,因为它将具有需要匹配的规则,以便客户有资格获得激励。 此功能将处理我们激励计划的逻辑。

<?php /** * Will extract the Variation ID if available otherwise it will get the Product ID * @param $product Product * @param bool $check_variations Whether or not to check for variation IDs * @return mixed */ function get_id_from_product( $product, $check_variations = true ) { // Are we taking variations into account? if( $check_variations ) { // Ternary Operator // http://php.net/manual/en/language.operators.comparison.php return ( isset( $product['variation_id'] ) && ! empty( $product['variation_id']) && $product['variation_id'] != 0 ) ? $product['variation_id'] : $product['product_id']; } else { // No variations, just need the product IDs return $product['product_id']; } } /** * Checks the existence of a specific product in the cart * @param $product_required The Product ID required to be in the cart * @return bool */ function qualifies_basedon_specific_product( $product_required ) { /* * We only want to run this on the cart or checkout page */ if( is_cart() || is_checkout () ) { foreach( WC()->cart->cart_contents as $key => $product_in_cart ) { if( $product_required == get_id_from_product( $product_in_cart ) ) { return true; } } // Return false in case anything fails return false; } } /** * Checks the cart for the weight required to qualify for the incentive * @param $weight_required Weight Required * @return bool */ function qualifies_basedon_weight( $weight_required ) { /* * We only want to run this on the cart or checkout page */ if( is_cart() || is_checkout () ) { if( $weight_required >= WC()->cart->cart_contents_weight ) { return true; } } // Return false in case anything fails return false; } /** * Checks the cart for the Total excluding taxes * @param $total_required * @return bool */ function qualifies_basedon_cart_total( $total_required ) { /* * We only want to run this on the cart or checkout page */ if( is_cart() || is_checkout () ) { if( WC()->cart->subtotal_ex_tax >= $total_required ) { return true; } } // Return false in case anything fails return false; } /** * Checks the cart to verify whether or not a product from a Category is in the cart * @param $category Accepts the Product Category Name, ID, Slug or array of them * @return bool */ function qualifies_basedon_product_category( $category ) { foreach( WC()->cart->cart_contents as $key => $product_in_cart ) { if( has_term( $category, 'product_cat', get_id_from_product( $product_in_cart, false ) ) ) { return true; } } // Return false in case anything fails return false; } /** * Adds a specific product to the cart * @param $product_id Product to be added to the cart */ function add_incentive_to_cart( $product_id ) { // Check the cart for this product $cart_id = WC()->cart->generate_cart_id( $product_id ); $prod_in_cart = WC()->cart->find_product_in_cart( $cart_id ); // Add the product only if it's not in the cart already if( ! $prod_in_cart ) { WC()->cart->add_to_cart( $product_id ); } } /** * Removes a specific product from the cart * @param $product_id Product ID to be removed from the cart */ function remove_incentive_from_cart( $product_id ) { $prod_unique_id = WC()->cart->generate_cart_id( $product_id ); // Remove it from the cart by un-setting it unset( WC()->cart->cart_contents[$prod_unique_id] ); }

As you can see, these functions return ‘True’ or ‘False’ so it’s going to make it really easy for us to mix it up and create an incentive program that is really flexible. What’s left to do now is come up with the rules you want to set for your customers to qualify for the incentive product and write the qualifies_for_incentive() function which will be tied to the woocommerce_check_cart_items WooCommerce action.

如您所见,这些函数返回“ True”或“ False”,这将使我们很容易将它们混合在一起并创建一个非常灵活的激励计划。 现在剩下要做的就是为客户设置要获得激励产品资格的规则,并编写woocommerce_check_cart_items qualifies_for_incentive()函数,该函数将与woocommerce_check_cart_items WooCommerce操作绑定。

<?php /** * Checks whether or not the customer qualifies for the incentive */ add_action( 'woocommerce_check_cart_items', 'qualifies_for_incentive' ); function qualifies_for_incentive() { }

Below are some examples of how you can use these functions to create something really unique.

下面是一些示例,说明如何使用这些功能创建真正独特的内容。

只有一项要求 (Only One Requirement)

Here are a few examples setting only one requirement.

以下是一些仅设置一项要求的示例。

购物车中已有特定产品 (Specific Product Existing in the Cart)
<?php // Specific product existing in the cart function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_specific_product( 70 ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }
购物车中所有产品的最小重量 (Minimum Weight of All the Products in the Cart)
<?php // Minimum weight of all the products in the cart function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_weight( 10 ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }
购物车的不含税总额 (Cart’s Total Excluding Taxes)
<?php // Cart's Total Excluding Taxes function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_cart_total( 199 ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }
购物车中某个类别的产品 (Product from a Category in the Cart)
<?php // Product From A Category In The Cart function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_product_category( 'premium-quality' ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }

混合起来 (Mixing It up)

Since we have a very flexible codebase, you can mix it up and truly make your incentive program unique. Below are some more examples showing how easy it is to add more conditions as necessary.

由于我们的代码库非常灵活,您可以将其混合使用,并真正使您的激励计划独特。 以下是一些更多示例,显示了根据需要添加更多条件的难易程度。

购物车中某个类别的产品或最小购物车总数 (Product from a Category in the Cart or Minimum Cart Total)
<?php // Product From A Category In The Cart OR Minimum Cart Total function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_product_category( 'premium-quality' ) || qualifies_basedon_cart_total( 199 ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }
类别中的产品和最低购物车总计 (Product from a Category and Minimum Cart Total)
<?php // Product From A Category AND Minimum Cart Total function qualifies_for_incentive() { // Incentive product we are giving away $incentive_product_id = 102; if( qualifies_basedon_product_category( 'premium-quality' ) && qualifies_basedon_cart_total( 199 ) ) { add_incentive_to_cart( $incentive_product_id ); } else { remove_incentive_from_cart( $incentive_product_id ); } }

You can even get more advanced than that and create more complex scenarios. The next step for you would be to turn this into a ‘Class’ so that you can have more than one incentive program, each with it’s own unique set of rules for qualifying.

您甚至可以得到更高级的信息,并创建更复杂的方案。 下一步是将其变成“班级”,这样您就可以拥有多个激励计划,每个激励计划都有一套自己独特的资格规则。

That’s it for this article. In the third part of this series we will be working with actions and filters that run on the New Product/Edit Product screens. We’ll then explore how to add custom fields to the ‘Product Screens’ using nothing but the API.

本文就是这样。 在本系列的第三部分中,我们将使用在“新产品/编辑产品”屏幕上运行的操作和过滤器。 然后,我们将探讨如何仅使用API​​将自定义字段添加到“产品屏幕”。

翻译自: https://www.sitepoint.com/woocommerce-actions-and-filters-manipulate-cart/

相关资源:WooCommerce购物车插件汉化中文版+集成支付宝担保交易+及时到账&财付通+银联
最新回复(0)