Site logo

Archived topic

Custom # of Posts

4 replies · Started by Matt on December 27, 2016

Viewing posts 1–5 of 5

I have a custom category page for photo posts that shows a thumbnail for each gallery post. How would I override the number of posts displayed within that particular template? Is there a way to do that? Here's my template code:

<?php
/**
 * The template for displaying Photo Category pages.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package GeneratePress
 */
 
// No direct access, please
if ( ! defined( 'ABSPATH' ) ) exit;

get_header(); ?>

	<section id="primary" <?php generate_content_class(); ?>>
		<main id="main" <?php generate_main_class(); ?>>
		<?php do_action('generate_before_main_content'); ?>
		<?php if ( have_posts() ) : ?>
			<?php do_action( 'generate_archive_title' ); ?>
            
            <div class="inside-article">

            <?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

                <div class="post-thumbnail">
                    <p class="thumbnail-image"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail' ); ?></a></p>
                    <p class="thumbnail-link"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
                </div>
            
			<?php endwhile; ?>
            </div>

			<?php generate_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<?php get_template_part( 'no-results', 'archive' ); ?>

		<?php endif; ?>
		<?php do_action('generate_after_main_content'); ?>
		</main><!-- #main -->
	</section><!-- #primary -->

<?php 
do_action('generate_sidebars');
get_footer();

Unless someone has a better way of doing this, I was able to do this by changing this:
<?php while ( have_posts() ) : the_post(); ?>

to this:
<?php query_posts('showposts=20&cat=2'); while ( have_posts() ) : the_post(); ?>

query_posts() works, but should be avoided if possible.

You might be able to do this:

add_action( 'pre_get_posts', 'set_posts_per_page_for_towns_cpt' );
function set_posts_per_page_for_towns_cpt( $query ) {
  if ( !is_admin() && $query->is_main_query() && is_category( 'towns' ) ) {
    $query->set( 'posts_per_page', '10' );
  }
}

You'll need to change the is_category() conditional to suit your needs.

I figured there would be a better way to do it; thanks!!!

No problem :)

This archived topic is closed to new replies.