Add a Products Per Page dropdown for WooCommerce

It’s no lie that WooCommerce is an amazing ecommerce tool for WordPress. It’s always my go-to plugin for creating stores of all types and sizes.

While the product archive pages have a great layout and sorting ability – one aspect I think every store can benefit from is a ‘show x products per page’ ability – as seen on most retail stores online. WooCommerce doesn’t do this by default – however some themes do include it. But you can add this to any theme with the following snippet by placing it in your functions.php file or standalone plugin.

Whats cool about this snippet is when the user has selected an option from the dropdown, it will autoload the page without having an additional button to click to update. You can also change the values of the ‘per page’ options as well.

// add a products per-page select dropdown to archive - above shop productloop
add_action( 'woocommerce_before_shop_loop', 'pro_selectbox', 25 );
function pro_selectbox() {
$per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);
echo '<div class="woocommerce-perpage">';
echo '<select onchange="if (this.value) window.location.href=this.value">';
$orderby_options = array(
'9' => '9',
'12' => '12',
'24' => '24',
'300' => 'All'
);
foreach( $orderby_options as $value => $label ) {
echo "<option ".selected( $per_page, $value )." value='?perpage=$value'>$label</option>";
}
echo '</select>';
echo '</div>';
}
add_action( 'pre_get_posts', 'pro_pre_get_products_query' );
function pro_pre_get_products_query( $query ) {
$per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);
if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'product' ) ) {
$query->set( 'posts_per_page', $per_page );
}
}

Hope that helps.

You can then style the dropdown (I implemented Select2 to modify the dropdown in the example below).

Useful post? Share it

Leave a Reply

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