woocommerce 分类到菜单,每页添加产品下拉菜单到woocommerce

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值