我不知道下面的代码是最好的代码,但它解决了我的问题
function relatedBlogPost($atts){
global $post;
//this the the custom post type
$args_cat = array(
\'taxonomy\' => \'blogs_cat\',
\'orderby\' => \'name\',
\'show_count\' => 1,
\'pad_counts\' => 1,
\'hierarchical\' => 1,
\'echo\' => 0
);
$categories = get_the_terms($post->ID, "blogs_cat"); // getting the category id of the current post
$args = array(
\'post_type\' => \'blog\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 3,
\'tax_query\' => array(
array(
\'taxonomy\' => \'blogs_cat\',
\'field\' => \'slug\',
\'terms\' => $categories[0]->slug // sending the current category slug name
),
),
\'post__not_in\' => array ($post->ID),
\'order\' => \'DEC\'
);
$related = new WP_Query($args);
if( $related->have_posts() ) {
$data=\'<h2 class="sectionHeading pb-5">Related Blog</h2>\';
$data .= \'<div class="main-Blog"><ul>\';
while( $related->have_posts() ) {
$related->the_post();
//displaying the category name
$terms = get_the_terms( $related->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></div>\';
return $data;
wp_reset_postdata();
}
}
add_shortcode( \'related-blog-post\', \'relatedBlogPost\');