1

I am displaying custom post types, grouped under their custom taxonomies (basically used @ChipBennett's answer from here: Display all posts in a custom post type, grouped by a custom taxonomy) for a products section of the site.

But, I'd like to limit the number of products that are initially displayed. Say, show 4, and if there are more than 4 products under that category, then I'd like to add a "load more products" link, which when clicked, loads the remaining products in that category onto the page.

I can do that with some JS (initially showing only the :nth-child(-n+4) while hiding the rest), but I suspect there's a more elegant and a less resource-intensive solution using WP/PHP.

<section id="products" class="padd-me">
  <h1 class="heading centered main-color">Our Products</h1>

  <?php
  $productCategories = get_terms( 'product_taxonomy' );
  foreach ( $productCategories as $productCategory ) {
    $productQuery = new WP_Query( array(
        'post_type' => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_taxonomy',
                'field' => 'slug',
                'terms' => array( $productCategory->slug ),
                'operator' => 'IN'
            )
        )
    ) );

    if ( $productQuery->have_posts() ) {
      ?>
      <div class="product-row">
        <div class="product-title">
          <h3><?php echo $productCategory->name; ?></h3>
        </div>
      <div class="product-pics-wrap">
      <?php
      while ( $productQuery->have_posts() ) {
        $productQuery->the_post();
        $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
        ?>
        <a href="<?php the_permalink(); ?>">
          <div class="product-pic" style="background-image:url(' <?php echo $backgroundImg[0] ?>');"></div>
        </a>
        <?php
       }
      ?>
        </div>
        <div class="more-products-link-wrap">
          <a class="more-products" href="#">see all products</a>
        </div>
      </div>
      <?php
    };
    ?>

    <?php
    // Reset things, for good measure
    $productQuery = null;
    wp_reset_postdata();
  }
?>
0

You can extend your QP Query with posts_per_page

Read more here at codex.

and then, use AJAX to load more on a button click or page scroll.

| improve this answer | |
  • Thanks. I've managed to limit it to 4 using posts_per_page, but I don't know how to load the rest... – sashaikevich Sep 13 '18 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.