Rewriting search and pagination base

there are 3 steps towards achieving your goal.

1 – Rewrite rules – wordpress needs to know what to look for and what to map it to

add_rewrite_rule( 'suche/([^/]+)/?$', 'index.php?s=$matches[1]', 'top' );
add_rewrite_rule( 'suche/([^/]+)(/seite/(\d+))/?$', 'index.php?s=$matches[1]&paged=$matches[3]', 'top' );

The above adds straight rewrite rules to the rewrite rules array so anytime someone goes to a URL like /suche/apfel/ it is translated internally as index.php?s=apfel.

2 – Redirect searches to our new structure

// redirect immediately
if ( isset( $_GET[ 's' ] ) ) {
    $location = '/suche/' . $_GET[ 's' ];
    if ( isset( $_GET[ 'paged' ] ) && $_GET[ 'paged' ] )
        $location .= '/seite/' . $_GET[ 'paged' ];
    wp_redirect( trailingslashit( home_url( $location ) ), 301 );
    exit;
}

Place this in your functions.php. As soon as a search request is detected wordpress will redirect to the nice search URL and the browser will remember the redirection because of the 301 status we’re passing to wp_redirect().

We are building our replacement URL for a search here, and if the $paged parameter is present we add that too.

3 – Create pagination links

function pagination_links( $type="plain", $endsize = 1, $midsize = 1 ) {
    global $wp_query, $wp_rewrite;
    $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

    // Sanitize input argument values
    if ( ! in_array( $type, array( 'plain', 'list', 'array' ) ) ) $type="plain";
    $endsize = (int) $endsize;
    $midsize = (int) $midsize;

    // Setup argument array for paginate_links()
    $pagination = array(
        'base'          => home_url( '/suche/' . get_search_query() . '%_%' ),
        'format'        => '/seite/%#%/', // ?page=%#% : %#% is replaced by the page number
        'total'         => $wp_query->max_num_pages,
        'current'       => $current,
        'show_all'      => false,
        'end_size'      => $endsize,
        'mid_size'      => $midsize,
        'type'          => $type,
        'prev_next'     => false
    );

    return paginate_links( $pagination );
}

The only thing you were missing in this function was using the modified format and base arguments to create the nice URL base of the current search and the nice URL page argument.

That should do what you need. You can dig deeper and remap more URLs to use translations using other filters but there are quite a few so this is a good starting point!

Leave a Comment