I want to categorise posts and show them on my WordPress website. So in order to achieve that I've written a code. My code is below.
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'travel',
'posts_per_page' => 5
) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul >';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
} else {
// if no featured image is found
$string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
}
}
} else {
// no posts found
$string .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
This code works perfectly fine. However, I want to show posts meta descriptions as well (i.e post created date and the category). How would I achieve that? Right now It only extracts the post heading and the image. Thanks so much for helping me out.
CodePudding user response:
Try this:
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'travel',
'posts_per_page' => 5
) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul >';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">';
if ( has_post_thumbnail() ) {
$string .= get_the_post_thumbnail($post_id, array( 50, 50) );
}
// title
$string .= get_the_title();
// date
$string .= get_the_date();
// categories
$categories = get_the_category();
$category_list = join( ', ', wp_list_pluck( $categories, 'name' ) );
$string .= wp_kses_post( $category_list );
// close link
$string .= '</a></li>';
}
// no posts found
$string .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
I guess you need/want to add HTML tags around date and category.
For example:
$string .= '<span >'.get_the_date().'</span>';
But that's up to you.
You can change the output of the categories based on the docs here.