1

I have troubles with getting the posts primary set category. How should I achieve this?

My code:

global $post;
$terms = get_the_terms( $post->ID, 'event-categories');

if($terms) {
    foreach( $terms as $term ) {
        $cat_obj = get_term($term->term_id, 'event-categories');
        $cat_slug = $cat_obj->slug;
    }
}

and in my html

<div class="post_kachel <?php echo $cat_slug; ?>">
  • Anyone? If something is not clear, then please tell me - I'll try to explain it as best as I can. – SengelYTPI Nov 30 '18 at 12:18
0

Here you go. Add this to functions.php and call it from anywhere you want.

function get_post_primary_category($post_id, $term='category', $return_all_categories=false){
        $return = array();

        if (class_exists('WPSEO_Primary_Term')){
            // Show Primary category by Yoast if it is enabled & set
            $wpseo_primary_term = new WPSEO_Primary_Term( $term, $post_id );
            $primary_term = get_term($wpseo_primary_term->get_primary_term());

            if (!is_wp_error($primary_term)){
                $return['primary_category'] = $primary_term;
            }
        }

        if (empty($return['primary_category']) || $return_all_categories){
            $categories_list = get_the_terms($post_id, $term);

            if (empty($return['primary_category']) && !empty($categories_list)){
                $return['primary_category'] = $categories_list[0];  //get the first category
            }
            if ($return_all_categories){
                $return['all_categories'] = array();

                if (!empty($categories_list)){
                    foreach($categories_list as &$category){
                        $return['all_categories'][] = $category->term_id;
                    }
                }
            }
        }

        return $return;
    }   
  • You should add a description what do the function and how it is possible to use that inside the template files. – bueltge Mar 21 at 6:45
  • I have mentioned that this function should include inside the functions.php and possible to access from anywhere – amilaishere Mar 21 at 8:55
  • yep, but anywhere is not a good helping for starters, especially in the theme context. – bueltge Mar 21 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.