First of all, i’m not really a coder or programmer i just really need help as i’m currently modifying a theme i purchased.
So as the title says, i’d like to show the categories of a post (custom post).
Here’s the code I’ve found and used:
<?php $terms = get_the_terms( $post->ID , 'tvshows_categories' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'tvshows_categories' );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>, ';
}
?>
It works however i get an error if it’s showed in the different custom post.
Warning: Invalid argument supplied for foreach()
Is there a better code to display the categories of a custom post that won’t give me any error if it doesn’t display the categories?
PS: Im actually not using it on the post, but on the tag.php (im using the default tags for the 3 custom post type).
And also pardon my English. Thank you!
1 Answer
get_the_terms
returns an Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.
You can always check if your $terms
is an array or is_wp_error
.
To check if $terms
is an array:
<?php $terms = get_the_terms( $post->ID , 'tvshows_categories' );
if ( is_array( $terms ) && ! is_wp_error( $terms ) ) {
foreach ($terms as $term) {
$term_link = get_term_link($term, 'tvshows_categories');
if (is_wp_error($term_link))
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>, ';
}
}
?>
Or if you’re on a single post, you can always check if you’re on your custom post type.
To check if you’re on a custom post type on a single page:
<?php
if ( is_singular('YOUR_CUSTOM_POST_TYPE') ) {
$terms = get_the_terms($post->ID, 'tvshows_categories');
foreach ($terms as $term) {
$term_link = get_term_link($term, 'tvshows_categories');
if (is_wp_error($term_link))
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>, ';
}
}
?>