Hôm nay mình xin chia sẻ code để chèn bài viết liên quan vào giữa nội dung bài viết mà không cần dùng plugin.

Các bạn chỉ cần copy đoạn code và chèn vào functions.php của theme đang dùng là được. Code như sau:
// code list bài viết liên quan
function related_post_list() {
if(is_singular('post')) {
global $post;
ob_start();
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 5,
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {?>
<ul class="related-post">
<?php while ($my_query->have_posts()):$my_query->the_post(); ?>
<li class="related-post-item"><a href="<?php echo get_the_permalink(); ?>" title="<?php echo get_the_title(); ?>"><?php echo get_the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<style>
ul.related-post {
background: #e6f4ff;
padding: 15px;
list-style: none;
}
ul.related-post li {
margin-bottom: 0;
margin-left: 0;
}
ul.related-post li a {
color: #0092ff;
}
li.related-post-item::before {
content: "2022";
color: #0092ff;
padding-right: 5px;
}
</style>
<?php } // end if has post
} // end if $categories
$related_post = ob_get_contents();
ob_end_clean();
return $related_post;
} //end if is single post
else return;
}
// Code đếm số dòng trong văn bản
function count_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
//Chèn bài liên quan vào giữa nội dung
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$related_posts= related_post_list();
if ( is_singular('post')) {
return count_paragraph( $related_posts, 1, $content );
}
return $content;
}
Các bạn có thể điều chỉnh css ở phần <style></style> trong đoạn code trên.
Đoạn code trên sẽ chèn bài viết liên quan sau đoạn đầu tiên của nội dung, nếu các bạn muốn chèn dưới n đoạn thì sửa số 1 thành số n trong đoạn code count_paragraph( $related_posts, 1, $content );
Chúc các bạn chèn bài viết liên quan vào giữa nội dung dễ dàng theo ý mình.