WooCommerce Products Per Page

How to Create a Products Per Page Dropdown

If you have alot of products in your shop you may want to consider improving the user experience, one way is by giving the option to display more products on the page.

This can be achieved by adding a dropdown select box within the shop archive where visitors can choose how many products to display per page. You can see this in action via the live demo.

Once the visitor has selected an option we will use the “get” method for the pre_get_posts hook to change the shops WordPress query and display the correct amount of products.

The first step is to display a select box on the shop archive page. With some basic php we can echo a select box via the woocommerce_before_shop_loop hook.

add_action( 'woocommerce_before_shop_loop', 'ps_selectbox', 25 );
function ps_selectbox() {
	$per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT); 	
	echo '<div class="woocommerce-perpage">';
	echo '<span>Per Page: </span>';
	echo '<select onchange="if (this.value) window.location.href=this.value">';	
	$orderby_options = array(
		'8' => '8',
		'16' => '16',
		'32' => '32',
		'64' => '64'
	);
	foreach( $orderby_options as $value => $label ) {
		echo "<option ".selected( $per_page, $value )." value='?perpage=$value'>$label</option>";
	}
	echo '</select>';
	echo '</div>';
}

Some inline jQuery has been added so everytime the select box is changed the “products per page” varibale is sent to the browser.

The filter_input() function gets the external variable which in this case is the number of products to show and sanitizes it.

Now everything is in place we can run the pre_get_posts hook with number of products per page via the “get” method.

add_action( 'pre_get_posts', 'ps_pre_get_products_query' );
function ps_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 );
	}
}

This is the most simpliest of methods to add a “products per page” dropdown for your WooCommerce store, alternativle you could go about using an ajax method.

  • Desmond Inyoface

    Hi,
    I put this directly into the functions.php of my child theme and it doesn’t work. The dropdown shows but any option just takes me back to the front page of my store. Am I missing something obvious? Thanks!