• I would like to display only the top 3 posts from 3 selected categories on home page. All category pages can display 10 as usual.

    Any idea what to add to the loop to do this? Am using a child theme so can drop the code into the functions file – have found how to limit the post number on front but not specify categories (or add the name of them to the meta).

    Thanks in advance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • // The Query
    $the_query= new WP_Query( 'cat=1,2,3&posts_per_page=3' );
    
    // The Loop
    if ( $the_query->have_posts() ) {
    	echo '
    <ul>';
    	while ( $the_query->have_posts() ) {
    		$the_query->the_post();
    		echo '
    <li>' . get_the_title() . '</li>
    ';
    	}
    	echo '</ul>
    ';
    } else {
    	// no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata()
    // just replace your categry id with 1,2,3
    Thread Starter atimes2015

    (@atimes2015)

    Thanks for that, however it doesn’t work – maybe because the loop in my theme is slightly different to what you’ve posted.

    Can you let me know where to insert the Query and what loop adjustments I need to make?

    <?php
    		$paged = get_query_var( 'paged' ) ? (int) get_query_var( 'paged' ) : 1;
    		$page_title = __( 'Latest Articles', 'opti' );
    		$ignore_post = -1;
    
    		if ( $paged == 1 ) {
    			get_template_part( 'includes/featured' );
    		} else {
    			$page_title = sprintf( __( 'Recent Posts - page %d', 'opti' ), $paged );
    		}
    
    		if ( have_posts() ) {
    ?>
    
    		<div id="recent-posts" class="<?php echo $recent_colwidth; ?>">
    			<h3><?php echo $page_title; ?></h3>
    
    			<ul id="recent-excerpts">
    <?php
    
    			while( have_posts() ) {
    				the_post();
    				if ( $post->ID != $ignore_post ) {
    					get_template_part( 'content', 'home-loop' );
    				}
    			}
    ?>
    			</ul>
    <?php
    			get_template_part( 'includes/pagination' );
    ?>
    		</div><!--END RECENT/OLDER POSTS-->

    Thanks

    Thread Starter atimes2015

    (@atimes2015)

    How can I get the top three posts from three selected categories on front page?

    Is this even possible without a plugin?

    Thread Starter atimes2015

    (@atimes2015)

    I’ve tried using a function which will display only 3 posts from 1, 2 or 3 categories but I cant make it order them by category … any ideas?

    // Only top 3 posts from selected 3 cats
    add_action('pre_get_posts', 'ad_filter_categories');
    function ad_filter_categories($query) {
        if ($query->is_main_query() && is_home()) {
            $query->set('cat','1,2,3');
    		$query->set('posts_per_page', 9);
        }
    }

    Is there a ‘posts_per_category’ declaration and a way of ordering them as cat 2 first, then 3, then 1 instead of by date posted?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Display only top 3 posts from 3 categories on front page’ is closed to new replies.