How to add 2 posts under another post? Formatting should be intact

Your code is almost done and it’s missing a key point. Here’s the whole one you need to get it done (put in functions.php):

function add_2_articles_if_less_than_200( $content ) {
    global $post;

    if ( $post->post_type == 'post' ) {
        // Use $post->post_content here as its content is raw - not formatted with HTML.
        $count = mb_strlen( $post->post_content, 'UTF-8' );

        // If $count is less then 200 then add two more articles from the same category.
        if ( $count < 20000 ) {
            $current_post_id = $post->ID;

            $current_post_categories = wp_get_post_categories( $current_post_id );

            if ( ! empty( $current_post_categories[0] ) ) {
                $qry = new WP_Query(
                    array(
                        'cat'            => $current_post_categories[0],
                        'posts_per_page' => 2,
                        'post__not_in'   => array( $current_post_id ),
                    )
                );

                if ( $qry->have_posts() ) {
                    while ( $qry->have_posts() ) : $qry->the_post();
                        // Remove this current function from tag `the_content` to avoid infinite loop. This is the key to make it work!
                        remove_filter( 'the_content', 'add_2_articles_if_less_than_200', 20 );

                        $filtered_post_content = apply_filters( 'the_content', $qry->post->post_content );

                        // Add filter again, otherwise this whole function won't work.
                        add_filter( 'the_content', 'add_2_articles_if_less_than_200', 20 );

                        $content .= "
<div class="additional_post">
    <h3>" . $qry->post->post_title . "</h3>
    <div class="additional_post_content">$filtered_post_content</div>
</div>";
                    endwhile;
                }

                // Make sure you reset the query as your page does not end here.
                wp_reset_query();
            }
        }
    }

    return $content;
}

// Use priority 20 to make sure your function will run after WordPress default filter to avoid issues.
add_filter( 'the_content', 'add_2_articles_if_less_than_200', 20 );

Pay attention to the code, especially its comments! I hope it works for you.

Leave a Comment