Trying to add a drop-down on products listing to change the displayed number of products. I am working on the latest version of Wordpress (4.8.2) and Woocommerce (3.1.2).
This is my code on functions.php
//save and load the chosen option from session
function jc_get_products_per_page(){
global $woocommerce;
$default = 5;
$count = $default;
$options = jc_get_products_per_page_options();
// capture form data and store in session
if(isset($_POST['jc-woocommerce-products-per-page'])){
// set products per page from dropdown
$products_max = intval($_POST['jc-woocommerce-products-per-page']);
if($products_max != 0 && $products_max >= -1){
$woocommerce->session->jc_product_per_page = $products_max;
return $products_max;
}
}
// load product limit from session
if(isset($woocommerce->session->jc_product_per_page)){
// set products per page from woo session
$products_max = intval($woocommerce->session->jc_product_per_page);
if($products_max != 0 && $products_max >= -1){
return $products_max;
}
}
return $count;
}
add_filter('loop_shop_per_page','jc_get_products_per_page');
//set the options for the dropdown
function jc_get_products_per_page_options(){
$options = apply_filters( 'jc_products_per_page', array(
5 => __('5', 'woocommerce'),
10 => __('10', 'woocommerce'),
15 => __('15', 'woocommerce'),
20 => __('20', 'woocommerce')
));
return $options;
}
//display the dropdown on front-end
function jc_woocommerce_products_per_page(){
$options = jc_get_products_per_page_options();
$current_value = jc_get_products_per_page();
?>
<div class="products-per-page">
<span>View:</span>
<form action="" method="POST" class="woocommerce-products-per-page">
<select name="jc-woocommerce-products-per-page" onchange="this.form.submit()">
<?php foreach($options as $value => $name): ?>
<option value="<?php echo $value; ?>" <?php selected($value, $current_value); ?>><?php echo $name; ?></option>
<?php endforeach; ?>
</select>
</form>
</div>
<?php
}
add_action('woocommerce_after_shop_loop', 'jc_woocommerce_products_per_page', 1);
So the problem is that when I change the dropdown, the page reload but the number of displayed products stay the same. The default. Any idea what is going wrong?
Edit: I tried to add a return 2;
on the first row of the function and still doesn't work. So, it seems the add_filter
doesn't work