0
votes

I have to list all posts from a Wordpress custom post type and show only the title and his respective category created through a custom taxonomy. My code is here and I am with some problems at taxonomies.

<?php
$args = array(
    'post_type' => 'books',
    'posts_per_page' => -1);
$myposts = get_posts( $args );
$terms = get_the_terms( $post->ID , 'category' );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <h1><?php echo the_title(); ?></h1>
    <p>Category: <?php echo $term->name; ?></p>
<?php endforeach;
wp_reset_postdata();?>
3

3 Answers

1
votes
<?php $args = array(
          'post_type' => 'books',
          'posts_per_page' => -1,       
                'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug'

            ),
        ),
      );
     $myposts = new WP_Query($args);
     foreach ( $myposts as $post ) : setup_postdata( $post ) ?> 
      <h1><?php echo the_title(); ?></h1>
    <?php $categories = get_the_category( get_the_ID() ); ?>
    <?php if( ! empty( $categories ) ): ?>
        <?php foreach( $categories as $category ): ?> 
            <p>Category: <?php echo $category->name; ?></p>
            <?php break; ?>
        <?php endforeach; ?>
    <?php endif; ?>
<?php endforeach;
wp_reset_postdata();?>    

Note:- Now you will get all post which have category taxnomoy. You are doing in wrong way now you will get correct results if you find any problem. please let me know.

1
votes

Here's your updated code, try this:

<?php
$args = array(
    'post_type' => 'books',
    'posts_per_page' => -1);
$myposts = get_posts( $args );
$terms = get_the_terms( $post->ID , 'category' );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <h1><?php echo the_title(); ?></h1>
    <?php $categories = get_the_category( $post->ID ); ?>
    <?php if( ! empty( $categories ) ): ?>
        <?php foreach( $categories as $category ): ?> 
            <p>Category: <?php echo $category->name; ?></p>
            <?php break; ?>
        <?php endforeach; ?>
    <?php endif; ?>
<?php endforeach;
wp_reset_postdata();?>
0
votes

I got it! Thanks for all!

<?php
    $terms = get_terms( $post_taxonomy );
    $args = array(
        'post_type' => 'book',
        'posts_per_page' => -1,
        'post_taxonomy' => 'category',
    );
    $the_query = new WP_Query($args);
?>

<?php if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post();

    $category = get_the_terms( $post->ID, "category");
    $category_name = "";
        foreach ( $category as $term ) {
            $category_name .= $term->name.' ';
        }
    ?>

    <h1><?php the_title(); ?></h1>
    <p>Category: <?php echo $category_name; ?></p>


    <?php endwhile;  ?>
<?php endif; ?>