Programmatically Implementing WooCommerce Giveaway Features

Buy X get Y is a very common marketing method in e-commerce sales, WooCommerce has a lot of plug-ins to realize this function, today we do not use plug-ins, directly with the code to achieve this function.

The main code to implement the WooCommerce Giveaway feature

In the following code, we use the woocommerce_payment_complete Hook, after the user pays successfully, it will execute the wprs_add_products_to_order function to facilitate the goods in the order, if the order contains the product ID 123, add the product ID 456 to the order, and set the price to 0, so as not to change the total price of the order.

add_action('woocommerce_payment_complete', 'wprs_add_products_to_order', 9999);

/**
 * @param $order_id
 *
 * @return void
 */
function wprs_add_products_to_order($order_id)
{
    $order = wc_get_order($order_id);
    foreach ($order->get_items() as $item_id => $item) {
        $product_id = $item->get_product_id();
        if ($product_id && $product_id == 123) {
            $order->add_product(wc_get_product(456), 1, ['subtotal' => 0, 'total' => 0]);
            $order->save();
            //wc_downloadable_product_permissions( $order_id, true ); 如果需要添加下载权限,添加这段代码
            //wc_update_product_stock( wc_get_product( 456 ), 1, 'decrease' ); //如果需要减库存,添加这段代码
            break;
        }
    }
}

The above product ID 123 and 456 are written directly in the code, if you need to add the gift function of the product is more, we can add a custom field plugin for the product to dynamically set and get the two product ID.

Not just a simple giveaway function, based on the code in this article, we can also realize the simple commodity bundle package function, the specific code will not be put here, the need for friends can try it themselves.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *