Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Custom Pagination Permalinks in wordpress

Tags:

wordpress

I have an article with several pages in my wordpress blog. if for example i have the following link in my blog :

http://example.com/heartbreaking-photos any idea how can i change the link of the second page from

http://example.com/heartbreaking-photos/2 to http://example.com/heartbreaking-photos/CUSTOM-STRING

CUSTOM-STRING aimed to be a custom title inside the page

like image 858
Delashmate Avatar asked Jul 24 '16 11:07

Delashmate


1 Answers

To achieve this, you will need to do 2 things:

  1. Disable the default WordPress canonical redirect - this is necessary, because WordPress will always redirect to the /2/ page when it encounters the page parameter in the URL or query args.

  2. Add a custom rewrite rule to direct your custom title to the second page of your page - this is essentially necessary to allow the link format that you want.

In terms of code, this is what you need (this is a working solution, I've just tested it locally):

// Removes the canonical redirection
remove_filter( 'template_redirect', 'redirect_canonical' );

// Add custom rewrite rules
add_action( 'init', 'my_add_custom_rewrite_rules' );
function my_add_custom_rewrite_rules() {
    // Slug of the target page
    $page_slug = 'heartbreaking-photos';

    // Page number to replace
    $page_num = 2;

    // Title you wish to replace the page number with
    $title = 'custom-string';

    // Add the custom rewrite rule
    add_rewrite_rule(
        '^' . $page_slug . '/' . $title . '/?$',
        'index.php?pagename=' . $page_slug . '&page=' . $page_num, 'top'
    );
}

There are three things you might want to configure or change here:

  1. $page_slug - this is the slug of your page, in your case this is heartbreaking-photos
  2. $page_num - the number of your pagination page, in your case this is 2
  3. $title - the title you wish to use instead of your page number 2.

Feel free to alter the code as you wish, or copy it to cover more additional cases, similar to this one.

EDIT

Important: Once you use the code, go to Settings > Permalinks and click the "Save Changes" button. This will rebuild your rewrite rules, and is necessary for the solution to work.

Hope that helps. Let me know if you have any questions.

like image 92
Marin Atanasov Avatar answered Sep 25 '22 12:09

Marin Atanasov