Including related content in a simple article to enhance reader engagement.

Code chèn bài viết liên quan vào giữa nội dung bài viết đơn giản nhất

This content provides a code snippet to insert related posts in the middle of a WordPress post without using a plugin. By adding the given code to the functions.php file of the WordPress theme, related posts can be displayed within the content. The code checks for post categories, retrieves related posts, and displays them in the specified format. This method allows WordPress users to customize the display of related posts without relying on additional plugins. The code snippet provided helps improve the user experience by suggesting relevant content to readers within the post.

Today, I’m excited to share a simple code snippet that allows you to effortlessly insert related posts in the middle of your content without the need for a plugin.

All you need to do is copy the code provided below and paste it into the functions.php file of your theme. Here’s the code:

// 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%20echo%20get_the_permalink();%20?>" title="<?php echo get_the_title(); ?>"><?php echo get_the_title(); ?></a></li>                      
                    <?php endwhile;?>
                </ul>
            <?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;
}

You can easily customize the CSS within the code snippet to match your website’s style.

This code snippet will insert related articles after the first paragraph of your content. If you wish to insert them after a different paragraph, simply adjust the number in the code.

See also  Fix "post_max_size" smaller than "upload_max_filesize" error in Wordpress.

I hope this makes it easy for you to seamlessly insert related posts within your content. Feel free to reach out if you have any questions or need further assistance.

Rate this post

Related posts