Menu Close

WooCommerce: Automatically Add Tag To Purchased Products

default

This functionality can be helpful to those who need to differentiate purchased products from non-purchased ones. Think about a way to automatically discount non-tagged products, in order to entice more sales; or a function that only shows purchased products via a custom shortcode.

No matter the application, “tagging” products upon purchase is super easy. Of course, make sure to create a custom product tag first, and get its ID, so that you can use this in the code below. Enjoy!

Now that I’ve created the “Sold” product tag, the snippet below automatically assigns this to purchased products once the customer reaches the thank you page. I have now 7 products tagged as “Sold” and can use this for marketing purposes.

PHP Snippet: Auto-tag Products Upon Purchase @ WooCommerce Thank You Page

/**
 * @snippet       Programmatically Tag Products
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_thankyou', 'bbloomer_auto_tag_product' );

function bbloomer_auto_tag_product( $order_id ) {
	$order = wc_get_order( $order_id );
	$auto_tag_id = array( 12345 ); // YOUR TAG ID HERE
	foreach ( $order->get_items() as $item_id => $item ) {
		$product = $item->get_product();
		$tags = $product->get_tag_ids();
		if ( ! array_intersect( $tags, $auto_tag_id ) ) {
			$product->set_tag_ids( array_merge( $tags, $auto_tag_id ) );
			$product->save();
		}
	}
}
View Source
Posted in WooCommerce Tips