I want to display only 3 categories (Ex: horses, dogs, birds), names only and comma separated, in my Post, since one of them, two or all tree are marked in the post.
<span><?php
if ( 'in_category('horses') ) {
echo "horses";
} ?></span><span><?php
if ( in_category('dogs') ) {
echo "dogs";
} ?></span><span><?php
if ( in_category('birds') ) {
echo "birds";
}
?></span>
I want to display only 3 categories (Ex: horses, dogs, birds), names only and comma separated, in my Post, since one of them, two or all tree are marked in the post.
<span><?php
if ( 'in_category('horses') ) {
echo "horses";
} ?></span><span><?php
if ( in_category('dogs') ) {
echo "dogs";
} ?></span><span><?php
if ( in_category('birds') ) {
echo "birds";
}
?></span>
It should be enough using a single <span>
for all categories and add some logic.:
<span><?php
$categories = ['horses','dogs','birds'];
$string = "";
foreach ($categories as $category){ //iterate over the categories to check
if(has_category($category))
$string .= $category.", "; //if in_category add to the output
}
$string = trim($string); //remove extra space from end
$string = rtrim($string, ','); //remove extra comma from end
echo $string; //result example: <span>horses, dogs</span>
?></span>
I'm not sure, if I understand it correctly, because it doesn't sound like very common problem, but...
If you want to check only for the existence of given three categories and output them separated with commas, then this is the code you can use (based on yours, but I've fixed the empty spans problem):
<?php $cats_printed = 0; ?>
<?php if ( in_category('horses') ) : $cats_printed++; ?><span>horses</span><?php endif; ?>
<?php if ( in_category('dogs') ) : if ( $cats_printed++ ) echo ', '; ?><span>dogs</span><?php endif; ?>
<?php if ( in_category('birds') ) : if ( $cats_printed++ ) echo ', '; ?><span>birds</span><?php endif; ?>
Here's a simplified version of Fabrizo's code:
<span><?php
$categories = [ 'horses', 'dogs', 'birds' ];
echo implode( ', ', array_filter( $categories, 'has_category' ) );
?></span>
You can use get_the_terms( int|WP_Post $post, string $taxonomy )
. See Codex detail here.
// put IDs of your selected three categories e.g. 15, 18, 20 here in this array
$my_cats = array(15, 18, 20);
$my_terms = get_the_terms( get_the_id(), 'category' );
if ( ! empty( $my_terms ) ) {
if ( ! is_wp_error( $my_terms ) ) {
foreach( $my_terms as $term ) {
if(in_array($term->term_id, $my_cats){
// Display them as you want
echo '<span>' . esc_html( $term->name ) . '</span>' ;
}
}
}
}