How to get primary category name in WordPress new version

There is a new feature in wordpress introducing primary category.
When you select a category, primary category can be specified.

My question is how can I get that primary category name using WordPress Core functions?

if there is no function, can you help me to get the first child of main category?

for example:
– main category
— child cat 1
— child cat 2
— child cat 3

I need to get — child cat 1.

Thanks for you help.

7 Answers
7

I have editted the MMT Designer function. This works better for me:

if ( ! function_exists( 'get_primary_taxonomy_id' ) ) {
    function get_primary_taxonomy_id( $post_id, $taxonomy ) {
        $prm_term = '';
        if (class_exists('WPSEO_Primary_Term')) {
            $wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
            $prm_term = $wpseo_primary_term->get_primary_term();
        }
        if ( !is_object($wpseo_primary_term) || empty( $prm_term ) ) {
            $term = wp_get_post_terms( $post_id, $taxonomy );
            if (isset( $term ) && !empty( $term ) ) {
                return $term[0]->term_id;
            } else {
                return '';
            }
        }
        return $wpseo_primary_term->get_primary_term();
    }
}

Leave a Comment