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!
PHP Snippet: Auto-tag Products Upon Purchase @ WooCommerce Thank You Page
/**
* @snippet Programmatically Tag Products
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
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();
}
}
}
Hi there,
Great code. But is there a way to add a tag to out of stock products? I’d quite like to filter out of stock products using a tag.
Thanks!
Colin, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!