php - Getting Wordpress single post primary category -


i show primary category of single post when has multiple categories. using code @ moment:

<?php   $perma_cat = get_post_meta($post->id , '_category_permalink', true);   if ( $perma_cat != null ) {     $cat_id = $perma_cat['category'];     $category = get_category($cat_id);   } else {     $categories = get_the_category();     $category = $categories[0];   }   $category_link = get_category_link($category);   $category_name = $category->name;   ?>        <a href="<?php echo $category_link ?>"><?php echo $category_name ?></a> <span class="ion-ios-arrow-right"></span></li> 

can not find documentation @ moment. advise how improve?

please note work, if using yoast implement "primary" category - believe doing - code block (written jawinn on github) should work :

<?php  // show yoast primary category, or first category $category = get_the_category(); $usecatlink = true; // if post has category assigned. if ($category){     $category_display = '';     $category_link = '';     if ( class_exists('wpseo_primary_term') ){     // show post's 'primary' category, if yoast feature available, & 1 set     $wpseo_primary_term = new wpseo_primary_term( 'category', get_the_id() );     $wpseo_primary_term = $wpseo_primary_term->get_primary_term();     $term = get_term( $wpseo_primary_term );     if (is_wp_error($term)) {          // default first category (not yoast) if error returned         $category_display = $category[0]->name;         $category_link = get_category_link( $category[0]->term_id );     } else {          // yoast primary category         $category_display = $term->name;         $category_link = get_category_link( $term->term_id );     } }  else {     // default, display first category in wp's list of assigned categories     $category_display = $category[0]->name;     $category_link = get_category_link( $category[0]->term_id ); } // display category if ( !empty($category_display) ){     if ( $usecatlink == true && !empty($category_link) ){         echo '<span class="post-category">';         echo '<a href="'.$category_link.'">'.htmlspecialchars($category_display).'</a>';         echo '</span>';     } else {         echo '<span class="post-category">'.htmlspecialchars($category_display).'</span>';     } }  } ?> 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -