WordPress at Your Fingertips

Hierarchical Product Tags in WooCommerce

The task is to change the tags of products in woocommerce, so that they are displayed as hierarchical. In other words the code below is answer for the following quwstion: "How to make woocommerce product tags hierarchical?".

Heirarchical_WC_Tag::init();

/**
 * Makes woocommerce product tags tree-like.
 *
 * Also, allows you to specify the same prefix for cat
 * and tags taxonomies of product.
 *
 * @author Kama (wp-kama.com)
 * @version 0.1
 */
class Heirarchical_WC_Tag {

	public static function init(): void{

		//add_action( 'wp', [ __CLASS__, 'debug' ] );

		add_action( 'init', [ __CLASS__, 'modify_product_tag_taxonomy' ], 20 );
	}

	public static function debug( $wp ){
		print_r( get_queried_object() );
		print_r( $wp );
		print_r( $GLOBALS['wp_rewrite'] );
		exit;
	}

	public static function modify_product_tag_taxonomy(): void{
		global $wp_taxonomies;

		$cat = &$wp_taxonomies['product_cat'];
		$tag = &$wp_taxonomies['product_tag'];

		$tag->rewrite['hierarchical'] = true; // for term_link
		$tag->hierarchical = true;
		$tag->meta_box_cb = 'post_categories_meta_box';

		// Fix query vars, if friendly-URL prefix of cats and tags idential.
		if( $tag->rewrite['slug'] === $cat->rewrite['slug'] ){

			add_filter( 'request', [ __CLASS__, 'fix_product_tag_request_var' ] );
		}
	}

	public static function fix_product_tag_request_var( $vars ){

		if( ! empty( $vars['product_cat'] ) ){

			$_cat_patrs = explode( '/', $vars['product_cat'] );
			$_patrs_end = end( $_cat_patrs );

			$tag_exists = get_term_by( 'slug', $_patrs_end, 'product_tag' );

			if( $tag_exists ){
				$vars['product_tag'] = $vars['product_cat'];
				unset( $vars['product_cat'] );
			}
		}

		return $vars;
	}

}
No comments
    Log In