• Resolved donnytree

    (@donnytree)


    Hello,

    Thank you for the great plugin!

    I am trying to get the name of the permalink category to display, but the following code does not work:
    <div class="featured-cat"><?php $category = get_the_category(); echo $category[0]->cat_name; ?></div>

    The above code just displays the first category, which is ordered alphabetically. Is there any way I can get the main permalink category for display purposes? Something like what Yoast has done here: https://www.joshuawinn.com/using-yoasts-primary-category-in-wordpress-theme/ for example.

    Thank you in advance,
    Donna

Viewing 6 replies - 1 through 6 (of 6 total)
  • You can do this:

    <?php
      setup_postdata($post);
      $perma_cat = get_post_meta($post->ID , '_category_permalink', true);
      if ( $perma_cat != null ) {
        $cat_id = $perma_cat['category'];
        $cat = get_category($cat_id);
        $category_link = get_category_link($cat_id);
        $category_name = $cat->name;
      } else {               
        $cat = get_the_category();
        $category_link = get_category_link($category->term_id);
        $category_name = $cat[0]->cat_name;
      }
    ?>
    <a href="<?php echo $category_link ?>"><?php echo $category_name ?></a>
    • This reply was modified 7 years, 7 months ago by micdijkstra.

    Slightly updated version with a fix for the fallback category link:

    <?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>
    Plugin Author Jordy Meow

    (@tigroumeow)

    Great, I have added this in the FAQ ??

    Thread Starter donnytree

    (@donnytree)

    Thanks so much @micdijkstra, this works perfectly!

    Thread Starter donnytree

    (@donnytree)

    Sorry, I am noticing the following in my error logs:
    [Sat Apr 22 09:42:13 2017] [error] PHP Warning: Illegal string offset ‘category’ in on line 29

    Which is this line of code:
    $cat_id = $perma_cat[‘category’];

    Thread Starter donnytree

    (@donnytree)

    OK I added the following and the error seems to have stopped:
    if ( $perma_cat != null && is_array($perma_cat)) {

    So that it checks to make sure it’s an array.

    Thanks again!
    Donna

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘get primary category’ is closed to new replies.