I am creating a template for a custom post type called "Projects" and trying to display a list of all categories assigned to a single post.
<div >
<div >
<div >
<div >
<a href="/project" style="text-align: left;" >< Back to Projects</a>
<h2 ><?php echo get_the_title(); ?></h2>
<p ><?php echo $fields['subtitle']; ?></p>
<div >
<?php echo get_the_category_list( ' \ ' ); ?>
</div>
</div>
<div >
<?php echo get_the_content(); ?>
</div>
</div>
</div>
What shows up on the single post is just an empty div; no categories are coming in from the get_the_category_list function.
I tried changing this line:
<?php echo get_the_category_list( ' \ ' ); ?>
to this:
$args = array(
'taxonomy' => 'ecprojects',
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories($args);
foreach($cats as $cat) {
?>
<a href="<?php echo get_category_link( $cat->term_id ) ?>">
<?php echo $cat->name; ?>
</a>
<?php
}
?>
(ecprojects being the name of the custom post type), but got the same result.
CodePudding user response:
Try using <?php the_category(' \ ') ?>
instead of <?php echo get_the_category_list( ' \ ' ); ?>
(without echo
...)
CodePudding user response:
You can use get_the_terms() function for getting the terms object related to a post. use below example for your code. here 'ecprojects' should be taxonomy name.
Note: replace get_the_ID() with post_id if you are not in loop or post template.
$cats = get_the_terms( get_the_ID(), 'ecprojects');
foreach($cats as $cat) {
?>
<a href="<?php echo get_category_link( $cat->term_id ) ?>">
<?php echo $cat->name; ?>
</a>
<?php
}
?>
I hope it helps.