There is a new feature in wordPress introducing a Primary Category. When you select multiple categories for your Product or Post, You can specify a primary category. In this article i am going to show how to display your primary category of a Product or a Post.
For example:
- Main Category
1.1 Child Category 1
1.2 Child Category 2
1.3 Child Category 3
In the above example, Need to display “Main Category”
Yoast, WordPress SEO(Search Engine Optimization) Plugin brought with a new feature that the ability to set a Primary Category for a Post or Product. Now you will see Make Primary link when selecting multiple categories (or a “Primary” label if one has been set).
The WordPress SEO Plugin uses this when generating its Breadcrumb links. So the most important category will appear, rather than one of many categories that may be applied to a Post or a Product.
Note : This code isn’t officially provided by Yoast SEO. I figured it out by digging around the plugin. So it is possible that their API or functions could change in future versions and cause something to break. So just be aware of this before integrating into your custom WordPress :
$primary_cat_id = get_post_meta($product->id,'_yoast_wpseo_primary_product_cat',true); if($primary_cat_id){ $product_cat = get_term($primary_cat_id, 'product_cat'); if(isset($product_cat->name)) $category_link = get_category_link($primary_cat_id); echo '<a href = "'.esc_url( $category_link ).'" class="catName"> #'.$product_cat->name.'</a>'; }
Just Paste the above code to where you need to display the primary category name of a product.
In the above code Firstly, we are fetching Primary Category Name using WordPress get_post_meta() function after that we need to add Category archive link to Name of the Category.
Add Comment