I'm currently creating a shortcode for a post list in WordPress. And here's my code
function mgc_post_default() {
global $post;
extract(shortcode_atts(array(
'cat' => '',
'num' => '5',
'order' => 'DESC',
'orderby' => 'post_date',
), $atts));
$args = array(
'cat' => $cat,
'posts_per_page' => $num,
'order' => $order,
'orderby' => $orderby,
);
$output = '';
$posts = get_posts($args);
foreach($posts as $post) {
setup_postdata($post);
$output .= '<div class="movie-poster">' . get_the_post_thumbnail() . '</div>';
$output .= '<div><h2><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></h2></div>';
$output .= '<div>' . get_the_date() . '</div>';
$output .= '<div>' . get_the_content() . '</div>';
$output .= '<div>' . get_field( "status" ) . '</div>';
$output .= '<div>' . get_the_category( $id )[0]->name . '</div>';
$output .= '<div>' . get_the_tags( $id ) [1]->name . '</div>';
}
wp_reset_postdata();
return '<div>'. $output .'</div>';
}
// Register shortcode
add_shortcode('mgc_post', 'mgc_post_default');
It's working, but the category and tag of each post just appeared 1. What I want is it can show all categories and tags info of each post.
So my question is how to show all those categories and tags for each post?
Thank you,
CodePudding user response:
To retrieve all categories for a post, use wp_get_post_categories instead of get_the_category. Then you just loop over the categories inside your foreach.
Same for the terms. But then use wp_get_post_terms.
So something like this:
$posts = get_posts($args);
foreach($posts as $post) {
setup_postdata($post);
$categories = wp_get_post_categories( $post );
$foreach( $categories as $category ) {
$output .= '<div>' . $category->name . '</div>';
}
}
wp_reset_postdata();
CodePudding user response:
Thank you @anotheraccount for the answer, but I've solved my own problem by adding this code 'get_the_tag_list()
' and 'get_the_category_list()
' to the $output