Mục lục

Trong Flatsome hiện chưa có bài viết liên quan cùng danh mục vì vậy bạn cần phải bổ xung nó vào ở dưới phần bài viết, bạn hãy chép đoạn code dưới đây vào functions.php và sau đó vào Giao diện -> Tùy Biến -> Blog Single Post sau đó chèn với shortcode dưới đây
1 | [code_wp_related_posts count = "3" title= "Bài viết liên quan" ] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | function code_wp_related_posts_shortcode( $atts ) {
$atts = shortcode_atts( array (
'count' => 3,
'title' => 'Bài viết liên quan'
), $atts );
$post_id = get_the_ID();
$categories = get_the_category( $post_id );
if ( ! empty ( $categories ) ) {
$category_ids = array ();
foreach ( $categories as $category ) {
$category_ids [] = $category ->term_id;
}
$related_posts_args = array (
'post__not_in' => array ( $post_id ),
'posts_per_page' => $atts [ 'count' ],
'category__in' => $category_ids ,
'orderby' => 'rand' ,
);
$related_posts_query = new WP_Query( $related_posts_args );
$output = '<div class="container section-title-container"><h3 class="section-title section-title-normal"><b></b><span class="section-title-main">' . $atts [ 'title' ]. '</span><b></b></h3></div><div class="row large-columns-3 medium-columns- small-columns-1">' ;
if ( $related_posts_query ->have_posts() ) {
while ( $related_posts_query ->have_posts() ) {
$related_posts_query ->the_post();
$output .= '<div class="col post-item">' ; // Mở col
$output .= '<div class="col-inner">' ;
$output .= '<div class="box box-text-bottom box-blog-post has-hover">' ;
$output .= '<div class="box-image">' ;
$output .= '<div class="image-cover" style="padding-top:56%;">' ;
$output .= '<a href="' . get_the_permalink() . '" class="plain" aria-label="' . get_the_title() . '">' ;
$output .= get_the_post_thumbnail( get_the_ID(), 'medium' , array ( 'class' => 'attachment-medium size-medium wp-post-image' , 'loading' => 'lazy' ) );
$output .= '</a>' ;
$output .= '</div>' ;
$output .= '</div>' ;
$output .= '<div class="box-text text-left">' ;
$output .= '<div class="box-text-inner blog-post-inner">' ;
$output .= '<h5 class="post-title is-large">' ;
$output .= '<a href="' . get_the_permalink() . '" class="plain">' . get_the_title() . '</a>' ;
$output .= '</h5>' ;
$output .= '<div class="is-divider"></div>' ;
$output .= '<p class="from_the_blog_excerpt">' ;
$output .= get_the_excerpt();
$output .= '</p>' ;
$output .= '</div>' ;
$output .= '</div>' ;
$output .= '</div>' ;
$output .= '</div>' ;
$output .= '</div>' ;
}
wp_reset_postdata();
} else {
$output .= '<p>Không có bài viết liên quan nào.</p>' ;
}
$output .= '</div>' ;
return $output ;
}
return '' ; } add_shortcode( 'code_wp_related_posts' , 'code_wp_related_posts_shortcode' ); |
Và đây là thành quả mình.