Support » Developing with WordPress » How can you print 2 additional posts from the same category under a post?

  • There is an article on a WordPress blog.

    The goal is to check if the article has 200 words. If it does, do nothing extra. If it does not, print the 2 most recent articles from the same category underneith the article (and if possible do not print the same article if it happens to be one of the 2 most recent).

    Any idea what code would accomplish this?

    Coding level: beginner – not good at php

Viewing 3 replies - 1 through 3 (of 3 total)
  • This should solve your problem, add this to functions.php of your current active Theme/Child theme

    
    add_filter("the_content" , "add_2_articles_if_less_than_200");
    
    function add_2_articles_if_less_than_200($content) {
    
    	global $post;
    	if($post->post_type == "post") {
    		$count = word_count($content);
    		
    		if($count < 200) { //if count is less then 200 then add two more articles from the same category
    			$current_post_id = $post->ID;
    			$categries = wp_get_post_categories($current_post_id);
    			if(isset($categries[0])) {
    				$cat = $categries[0];
    				
    				$args = array(
    							"cat" => $cat,
    							"posts_per_page" => 2,
    							"post__not_in" => array($current_post_id)
    							);
    				$qry = new WP_Query($args);
    
    				while($qry->have_posts()) {
    					$qry->the_post();
    					$content .="
    							<div class='additional_post'>
    								<h3>".get_the_title()."</h3>
    								<div class='additional_post_content'>".get_the_content()."</div>
    							</div>
    					";
    				}
    
    				wp_reset_query();
    			}
    		}
    
    	}
    
    	return $content;
    }
    
    function word_count($content) {
        $word_count = str_word_count( strip_tags( $content ) );
        return $word_count;
    }

    Thanks. This code works well. Only, it doesn’t seem to carry over the linked headline, the featured image, or the paragraphs (it just prints the entire content in one paragraph, but does include the galleries from the other articles, which is nice)?

    • This reply was modified 1 year, 5 months ago by ordresser.

    Does anyone have a solution for this, please?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How can you print 2 additional posts from the same category under a post?’ is closed to new replies.