1. Tạo Shortcode bài viết liên quan
function create_shortcode_related_posts($args, $content) {
ob_start(); ?>
<?php
$tags = wp_get_post_terms( get_queried_object_id(), 'category', array('fields' => 'ids') );
$args = array (
'post__not_in' => array ( get_queried_object_id() ),
'posts_per_page' => 5,
'orderby' => 'rand',
'tax_query' => array (
array(
'taxonomy' => 'category',
'terms' => $tags
),
),
);
$tags_query = new wp_query( $args );
if( $tags_query->have_posts() ) { ?>
<ul class="related-posts">
<?php while( $tags_query->have_posts() ) {
$tags_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php }
wp_reset_postdata(); ?>
</ul>
<?php } ?>
<?php $group_list = ob_get_contents();
ob_end_clean();
return $group_list;
}
add_shortcode('related_posts', 'create_shortcode_related_posts');
2. Tạo 1 function xác định kết thúc số thẻ
function count_p( $insertion, $paragraph_id, $content ) {
$end_p = '</p>';
$paragraphs = explode( $end_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $end_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
3. Chèn Shortcode bài viết liên quan ở trên vào khi kết thúc thẻ
add_filter( 'the_content', 'add_related_post' );
function add_related_post( $content ) {
$related_posts= "<div class='meta-related'>".do_shortcode('[related_posts]')."</div>";
if ( is_single() ) {
return count_p( $related_posts, 2, $content );
}
return $content;
}