简体   繁体   中英

Pagination doesn't work with custom rewrite rules

I'm trying to show discounted products on Woocommerce at http://example.com/shop/discounted which works fine as long as there is just one page, but when pagination comes in, it doesn't work, and var_dump( get_query_var('paged') always returns 0 , i have defined two rewrite rules, one for when there is no pagination and one for when user navigates to next pages.

function dw_custom_rewrite_rules() {
    add_rewrite_endpoint( 'sortby', EP_ALL_ARCHIVES );

    add_rewrite_rule('^shop/discounted?', 'index.php?post_type=product&sortby=discounts', 'top');

    // With pagination
    add_rewrite_rule('^shop/discounted/page/?([0-9]{1,})/?$', 'index.php?post_type=product&sortby=discounts&paged=$matches[1]', 'top');

}
add_action('init', 'dw_custom_rewrite_rules');

I finally did manage to fix this, Thanks to this answer , i could'nt use the keyword paged i don't know why, so i just changed it to pageds , and then adding a little bit of extra code to the pre_get_posts hook ( with your own coditionals ofcourse ) :

add_action('pre_get_posts', function( $query ){
    $paged = (int) get_query_var( 'pageds', 1 );
    $query->set('paged', $paged);
});

then adding pageds to query_vars :

add_filter('query_vars', function( $vars ){
   $vars[] = 'pageds';

   return $vars;
});

and one more thing is we don't have to write two seperate rewrite rules, we can combine them like this :

function dw_custom_rewrite_rules() {
    add_rewrite_endpoint( 'sortby', EP_ALL_ARCHIVES );
    add_rewrite_rule('^shop/discounted(/page/([0-9]+)?)?/?$', 'index.php?post_type=product&sortby=discounts&pageds=$matches[2]', 'top');
}
add_action('init', 'dw_custom_rewrite_rules');

I don't use Wordpress, but usually you will never evaluate $matches[1] with single quotes. Try double quotes instead and check what does your variable output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM