I am having a custom taxonomy say "project-type" which is registered for the custom post "projects" and under that I have terms "catOne" and "catTwo". Now I want to display all the custom posts that are linked to catOne using the term_id of "catOne", which in my case is 9.
So I am successfully able to loop through all the posts but it is displaying only the ID but not all contents.
My approach:
$cat_id = 9;
$args = array(
'post_type' => 'projects',
'tax_query' => array(
array(
'taxonomy' => 'project-type',
'field' => 'term_id',
'terms' => array( $cat_id )
),
),
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<div id="post-<?php echo $post->ID; ?> <?php post_class(); ?>">
<h1 class="posttitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<div id="post-content">
<?php the_excerpt(); ?>
</div>
</div>
<?php } wp_reset_postdata();
Output I am getting
<div id="post-137 class=" ""="">
<h1 class="posttitle"><a href=""></a></h1>
<div id="post-content">
</div>
</div>
<div id="post-135 class=" ""="">
<h1 class="posttitle"><a href=""></a></h1>
<div id="post-content">
</div>
</div>
Can someone please help me with where I am going wrong?
Instead of using post_class()
, the_permalink()
, the_title()
, and the_excerpt()
, you should use the $post
object to get the data, just like you did with $post->ID
. The functions you've used should be called only if you're using a loop based on have_posts()
. You aren't, so replace them with:
post_class()
-> get_post_class( '', $post->ID )
the_permalink()
-> get_the_permalink( $post->ID )
the_title()
-> $post->title
the_excerpt()
-> $post->post_excerpt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.