I am using WordPress and I have to show the related blog by category. I have created a custom-type post. I tried the below code but the code is displaying the last category of the post.
Would you help me out with this issue?
function relatedBlogPost($atts){
global $post;
$custom_terms = get_terms('blogs_cat');
foreach($custom_terms as $custom_term) {
$args = array(
'post_type' => 'blog',
'post_status' => 'publish',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'blogs_cat',
'field' => 'slug',
'terms' => $custom_term->slug
),
),
'post__not_in' => array ($post->ID),
//'order' => 'DEC'
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$data='';
$data .= '<ul>';
while($loop->have_posts()){
$loop->the_post();
/*get category name*/
$terms = get_the_terms( $loop->ID , 'blogs_cat' );
foreach ( $terms as $term ) {
$catname=$term->name;
}
$data.= '<li> <a href="'.get_permalink().'">
<div class="main-blogBoxwrapper">
<img src="'.get_the_post_thumbnail_url().'">
<div class="blogCatname">
<h6><span>'.$catname.'</span></h6>
<h4>'.wp_trim_words(get_the_title(), 14, '...').'</h4>
<p>'.wp_trim_words(get_the_excerpt(), 20, '...').'</p>
</div>
</div>
</a></li>';
}
$data.='</ul>';
return $data;
wp_reset_postdata();
}
}
}
add_shortcode( 'related-blog-post', 'relatedBlogPost');
Would you help me out with this issue?