Hi Guido,
Replace your function with the below code.
function cats($echo = false) {
$terms = get_the_terms( get_the_ID(), 'event_cat' );
$post_terms = array();
foreach ( $terms as $term ) {
$post_terms[] = $term->slug;
}
if( $echo ){
echo implode( " ", $post_terms );
} else{
return $post_terms;
}
}
If parameter $echo is false, the function will return the categories in array format, can be used for further processing.
If set to true, it will print the categories separated by space.
Hope this helps.
Good day!
-
This reply was modified 4 years, 8 months ago by
Achyuth Ajoy.
Thread Starter
Guido
(@guido07111975)
Hi Achyuth,
Thanks!
First, I made a mistake in my function, first line should be:
$terms = get_the_terms( get_the_ID(), 'event_cat' );
You solution does work, but with debug on there’s an notification:
Warning: Invalid argument supplied for foreach() in..
Only appears when post has no category.. so guess I need to add a check for this.
Guido
Thread Starter
Guido
(@guido07111975)
Found a check, using wp_error.
This will work for me:
function cats() {
$terms = get_the_terms( get_the_ID(), 'event_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$post_terms[] = $term->name;
}
return implode( " ", $post_terms );
endif;
}
Thanks again!
Guido
function cats($echo = false) {
$terms = get_the_terms( get_the_ID(), 'event_cat' );
if( !empty( $terms ) ) {
$post_terms = array();
foreach ( $terms as $term ) {
$post_terms[] = $term->slug;
}
if( $echo ){
echo implode( " ", $post_terms );
} else{
return $post_terms;
}
}
}
Code updated to check whether the terms variable is empty, before looping.
-
This reply was modified 4 years, 8 months ago by
Achyuth Ajoy.
You’re welcome. Try to use term slug instead of term name. Term name may contain spaces which may break your css
-
This reply was modified 4 years, 8 months ago by
Achyuth Ajoy.
Thread Starter
Guido
(@guido07111975)
Ah, of course. Did not thought about this! Thanks.
Guido