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  Plugin tạo nút ẩn hiện nội dung và chặn Google index đoạn text Wordpress

Bài liên quan:

Thêm icon New vào tiêu đề bài viết mới đăng Wordpress
Pasted 4
Saobay collapse shortcode
Cac buoc tao mot API xo so
plugin tốt cho wp
Các việc cần làm khi bạn vừa thiết kế xong website
cách đăng nhập vps amz
Display post of special category by shortcode
Dự toán chi phí
Chat bằng Facebook
Chat bằng Zalo
Chat hoặc gọi Telegram