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 9 years, 1 month 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>
Great, I have added this in the FAQ 🙂
Thanks so much @micdijkstra, this works perfectly!
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’];
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