What’s the WP way to load remaining custom posts?

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();
}
?>

Read more here:: What’s the WP way to load remaining custom posts?

Leave a Reply

Your email address will not be published. Required fields are marked *