0

I would like to get_the_category inside the_post_navigation. I created a custom field on Categories to assign a hex color to each category. I would like to use this color as the next / prev link background color when hovering on the post navigation.

How can I get the id of the category of the "next" or "prev" post?

I should clarify that every post has only two categories and I am only trying to get the id of the second category.

4
  • Theres an example at the end of the site you can use. codex.wordpress.org/Next_and_Previous_Links
    – Cam
    Commented Feb 1, 2018 at 15:50
  • Sorry Cam - not following. The examples at the end of that page are related to Pages, not Posts. And the Post-related samples don't involve categories. Please clarify / elaborate. Commented Feb 1, 2018 at 15:59
  • $next_post = get_next_post(); var_dump($next_post); $cats= get_the_terms($next_post->ID) var_dump($next_post); exit; But what happens if there's more than one category on a post?
    – admcfajn
    Commented Feb 2, 2018 at 0:33
  • There will only ever be two categories and I need only [1] thanks for this - I will try in the morning! Commented Feb 2, 2018 at 0:35

1 Answer 1

0

Here was my final solution:

$next_post = get_next_post();
if (!empty( $next_post )){
  $next_categories = get_the_terms($next_post->ID,'category');
  $next_cat_data = get_option('category_'.$next_categories[1]->term_id);
  if (isset($next_cat_data['hex'])){
    echo "<style>div.nav-next:hover{background-color:".$next_cat_data['hex'].";} div.nav-next:hover span.post-title, div.nav-next:hover span.meta-nav {color:#f8f7f4;}</style>";
  }
}
$previous_post = get_previous_post();
if (!empty( $previous_post )){
  $prev_categories = get_the_terms($previous_post->ID,'category');
  $prev_cat_data = get_option('category_'.$prev_categories[1]->term_id);
  if (isset($prev_cat_data['hex'])){
    echo "<style>div.nav-previous:hover{background-color:".$prev_cat_data['hex'].";} div.nav-previous:hover span.post-title, div.nav-previous:hover span.meta-nav {color:#f8f7f4;}</style>";
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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