EduardET

Primary Category Yoast 2

Dec 13th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.51 KB | None | 0 0
  1. if ( !class_exists('WPSEO_Primary_Term') ) {
  2.     $category_index = 0;
  3.     foreach( $post->post_categories as $category ) {
  4.         $category_index++;
  5.         $separator =  $category_index < count(  $post->post_categories ) ? ', ' : '';
  6.         echo '<a href="'. esc_url( $category['permalink'] ) .'" title="' . esc_attr( $category['label'] ) . '">' . esc_html( $category['label'] ) . '</a>' . $separator;
  7.     }
  8. } else {
  9.     // SHOW YOAST PRIMARY CATEGORY, OR FIRST CATEGORY
  10.     $category = $post->post_categories;
  11.     $useCatLink = true;
  12.     // If post has a category assigned.
  13.     if ($category){
  14.         $category_display = '';
  15.         $category_link = '';
  16.  
  17.         // Show the post's 'Primary' category, if this Yoast feature is available, & one is set
  18.         $wpseo_primary_term = new WPSEO_Primary_Term( 'project_category', get_the_id() );
  19.         $wpseo_primary_term = $wpseo_primary_term->get_primary_term();
  20.         $term = get_term( $wpseo_primary_term );
  21.         if (is_wp_error($term)) {
  22.             // Default to first category (not Yoast) if an error is returned
  23.             $category_display = $category[0]->name;
  24.             $category_link = get_category_link( $category[0]->term_id );
  25.         } else {
  26.             // Yoast Primary category
  27.             $category_display = $term->name;
  28.             $category_link = get_term_link( $term->term_id );
  29.         }
  30.  
  31.         // Display category
  32.         if ( !empty($category_display) ){
  33.             if ( $useCatLink == true && !empty($category_link) ){
  34.             echo '<a href="'.$category_link.'">'.htmlspecialchars($category_display).'</a>';
  35.             } else {
  36.             echo '<span class="post-category">'.htmlspecialchars($category_display).'</span>';
  37.             }
  38.         }
  39.        
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment