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; } ?>
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With