Shortcode lấy bài viết của danh mục WordPress

Tạo shortcode hiển thị bài viết của một danh mục WordPress gồm hình ảnh và tiêu đề dạng list.

Display post of special category by shortcode

Chèn vào Functions.php:

function saobay_category_posts_shortcode($atts) {
ob_start();
$atts = shortcode_atts( array(
‘category’ => ”,
‘posts_per_page’ => 10,
‘order’ => ‘DESC’,
‘orderby’ => ‘date’,
), $atts );

$query = new WP_Query( array(
‘cat’ => $atts[‘category’],
‘posts_per_page’ => $atts[‘posts_per_page’],
‘order’ => $atts[‘order’],
‘orderby’ => $atts[‘orderby’],
) );

if ( $query->have_posts() ) { ?>
<div class=”category-posts”>
<?php while ( $query->have_posts() ) {
$query->the_post(); ?>
<div class=”category-post”>
<div class=”category-post-left-content”>
<span class=”post-title”><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></span>
<span class=”post-date”><?php the_time(‘F j, Y’); ?></span>
</div>
<div class=”category-post-right-image”>
<?php the_post_thumbnail(‘thumbnail’); ?>
</div>
</div>
<?php } ?>
</div>
<?php }
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode( ‘category_posts’, ‘saobay_category_posts_shortcode’ );

Thêm Css vào style.css

.category-post {
display: flex;
}
.category-post-left-content {
width: 90%;
padding: 5px;
}
.category-post-right-image {
width: 20%;
padding: 5px;
}
span.post-date {
font-size: 13px;
}

Sau đó sử dụng shortcode:

[category_posts category=”18″ posts_per_page=”6″]

Thay 18 = ID của category, 6 = số bài viết muốn hiển thị.

Xem thêm  Các bước tạo một API xổ số

Viết một bình luận