I'm trying to add a 'products per page' dropdown to my woocommerce storefront child theme without using a plugin. I'm adding the below code to my functions.php source
add_action( 'woocommerce_before_shop_loop', 'ps_selectbox', 25 );
function ps_selectbox() {
$per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);
echo '
echo 'Per Page: ';
echo '';
$orderby_options = array(
'8' => '8',
'16' => '16',
'32' => '32',
'64' => '64'
);
foreach( $orderby_options as $value => $label ) {
echo "$label";
}
echo '';
echo '
}
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 );
}
}
When I do this, the drop down box shows but any option I choose just takes me back to the front page of my theme.
Can anyone help me?
解决方案You can add the below codes into functions.php file.
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 '
echo 'Per Page: ';
echo '';
$orderby_options = array(
'8' => '8',
'16' => '16',
'32' => '32',
'64' => '64'
);
foreach( $orderby_options as $value => $label ) {
echo "$label";
}
echo '';
echo '
}
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.