Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get primary category if more than one is selected?

Tags:

In Wordpress, how can I revert to the primary category?

I'm using the following loop, if all three are checked then it just reverts to the last term. I want to make sure it's the primary category.

<?php $term_list = wp_get_post_terms($post->ID, 'category', array("fields" => "names")); foreach ($term_list as $term) {     $name = $term; } ?> 

enter image description here

like image 876
Rob Avatar asked Mar 30 '17 10:03

Rob


People also ask

How do you get primary category Yoast?

With Yoast SEO, you can easily select the primary category when you are editing a post. Go to the Categories setting in the sidebar of the post editing screen. Click on the dropdown menu under Select the primary category.

How do I find primary category in WordPress?

WordPress is a great platform, but there is no built-in function to get the primary category for a post. This function accepts the following parameters: $post_id : the post ID, for which we want the categories. $term : By default it is set to 'category', but you may set it to any other taxonomy, such as post_tag.

What does primary category mean?

Primary category–The category where the consumer searches for the product. This category is in the storefront catalog, and sets which attributes are used to define the product.

How do I find the category of a WordPress post?

Now, if you want to display all your posts from a specific category on a separate page, WordPress already takes care of this for you. To find the category page, you simply need to go to Posts » Categories » View page and click on the 'View' link below a category.


1 Answers

This is not a native wordpress feature, but a feature of Yoast SEO (see here).

You can check for primary status the following way:

<?php $term_list = wp_get_post_terms($post->ID, 'category', ['fields' => 'all']); foreach($term_list as $term) {    if( get_post_meta($post->ID, '_yoast_wpseo_primary_category',true) == $term->term_id ) {      // this is a primary category    } } ?> 

If you are using custom taxonomies, use the meta_key

_yoast_wpseo_primary_CUSTOM_TAXONOMY 

instead.

like image 151
David Vielhuber Avatar answered Sep 29 '22 12:09

David Vielhuber