Ian Butler
Ian Butler

Reputation: 393

WordPress - How to get the category name in WP_Query

I'm querying custom posts types and can't get the name of the category the post belongs to. Feel like I've tried everything but sure it must be possible!

                        <?php
global $wpdb;
$currentuser_id = get_current_user_id();
$args = array(
                'post_type' => 'location',
                'author' => $currentuser_id,
);                  
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post(); ?>
        <div class="pindex">
           <?php if ( has_post_thumbnail() ) { ?>
                <div class="pimage">
                    <?php the_post_thumbnail(); ?>
                </div>
            <?php } ?>
            <div class="ptitle">
                <h2><?php echo get_the_title(); ?></h2>
            </div>
                            <div class="pcategory">

                            </div>
        </div>
    <?php endwhile;
    if (  $query->max_num_pages > 1 ) : ?>
        <div id="nav-below" class="navigation">
            <div class="nav-previous"><?php next_posts_link( __( '<span     class="meta-nav">&larr;</span> Previous', 'domain' ) ); ?></div>
            <div class="nav-next"><?php previous_posts_link( __( 'Next     <span class="meta-nav">&rarr;</span>', 'domain' ) ); ?></div>
        </div>
    <?php endif;
endif;
wp_reset_postdata();
?>

Does anybody know the code that would go between the below to get the category name?

<div class="pcategory">
</div>

Thanks in advance for any help!

Upvotes: 0

Views: 2557

Answers (1)

Ian Butler
Ian Butler

Reputation: 393

<?php
$terms = get_the_terms( $post->ID , 'gd_placecategory' );
foreach ( $terms as $term ) {
      echo $term->name;
}
?>

As it's a custom post type get_the_terms() is required

Note that you pass the custom post type into the WP_Query - 'location' in this case, however you need the custom taxonomy in get_the_terms() 'gd_placecategory'

Upvotes: 1

Related Questions