Filter the URL of next_posts_link & previous_posts_link

I am working with the qTranslate plugin to create a multi-lingual website. The plugin does a great job of translation except for on the next_posts_link & previous_posts_link template tags.

When a user has selected a different language the URL should change from:

Read More

http://mysite.com/test/page/2 (for default language)

to

http://mysite.com/fr/test/page/2 (for french language)

The plugin provides functions for modification/translation of URLs using the qtrans_convertURL($url) function. The problem I am having is finding a suitable hook or filter that will allow me to modify the URL output by the next_posts_link & previous_posts_link template tags.

The closest two WordPress filters I have found are:

add_filter('next_posts_link_attributes', 'my_next_attr');
add_filter('previous_posts_link_attributes', 'my_prev_attr');

Any tips would be most welcome.

Related posts

Leave a Reply

2 comments

  1. Run a filter on get_pagenum_link and you should be able to do what you want.

    The next_posts_link / previous_posts_link functions each call functions that in turn call other functions, which eventually route back to the get_pagenum_link function which provides a filter by the same name.

    It should give you the control you need, though post a comment if you specifically need an example.

    For the singular post link functions, ie. next_post_link / previous_post_link (note the non-plural other readers) there’s a filter hook with a matching name, eg. next_post_link and previous_post_link..

  2. Thanks to the helpful tip from @t31os the issue can be fixed with the following code:

    /***************************************************************
    * Function qtranslate_next_previous_fix
    * Ensure that the URL for next_posts_link & previous_posts_link work with qTranslate
    ***************************************************************/
    
    add_filter('get_pagenum_link', 'qtranslate_next_previous_fix');
    
    function qtranslate_next_previous_fix($url) {
        return qtrans_convertURL($url);
    }
    

    This fix works for custom post types too.

    Updated

    This second function ensures that the next_post_link & previous_post_link template tags are also filtered correctly on custom post types.

    /***************************************************************
    * Function qtranslate_single_next_previous_fix
    * Ensure that the URL for next_post_link & previous_post_link work with qTranslate
    ***************************************************************/
    
    add_filter('next_post_link', 'qtranslate_single_next_previous_fix');
    add_filter('previous_post_link', 'qtranslate_single_next_previous_fix');
    
    function qtranslate_single_next_previous_fix($url) {
        $just_url = preg_match("/href="([^"]*)"/", $url, $matches);
        return str_replace($matches[1], qtrans_convertURL($matches[1]), $url);
    }