Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Add class to links generated by next_posts_link and previous_posts_link

These two functions create anchor links, and you can customize a lot of it, but it's impossible to add a class through just using their parameters alone. Gotta add a function to functions.php:

add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');

function posts_link_attributes() {
    return 'class="styled-button"';
}

Reference URL

Comments

  1. Once again, thanks! I changed this a bit to accommodate different styles for next/previous. Here is what I did in case anyone else needs to have a class for each:

    add_filter('next_posts_link_attributes', 'posts_link_attributes_1');
    add_filter('previous_posts_link_attributes', 'posts_link_attributes_2');
    
    function posts_link_attributes_1() {
        return 'class="prev-post"';
    }
    function posts_link_attributes_2() {
        return 'class="next-post"';
    }
  2. another way to do this without a function would be to class an LI around each link:

    <!--BEGIN: Page Nav-->
    		<?php if ( $wp_query->max_num_pages > 1 ) : // if there's more than one page turn on pagination ?>
    
    	        <nav id="page-nav">
    	        	<h1 class="hide">Page Navigation</h1>
    		        <ul class="clear-fix">
    			        <li class="prev-link"><?php next_posts_link('« Previous Page') ?></li>
    			        <li class="next-link"><?php previous_posts_link('Next Page »') ?></li>
    		        </ul>
    	        </nav>
    
    		<?php endif; ?>
    		<!--END: Page Nav-->

    brent
    @
    mimoYmima.com

    check out our wordpress shell – html5.mimoymima.com

  3. Edward
    Permalink to comment#

    I like Brent’s method, except I used … as a wrapper around each link instead of tags. I was lazy and didn’t feel like writing the extra CSS for the list items, but worked just as well.

  4. Edward
    Permalink to comment#

    I like Brent’s method, except I used span tags to wrap around each link instead of li tags. I was lazy and didn’t feel like writing the extra CSS for the list items, but worked just as well.

  5. Chris
    Permalink to comment#

    I cannot get the ul/li approach to work. Styling is fixed what ever I do …. any ideas what I am doing wrong?

  6. Is it also possible to generate an “last_posts_link” ? If you have for example 5 result pages, you would jump to page 5 immediately..
    wp pagenavi uses it, but I won’t want to use that plugin.

  7. I liked Brent’s way of doing.

  8. Hi, thanks much!
    This solved half of my “problems”.. any idea how to add custom styles to next/previous_post_link? I tried the obvious way of adding next_post_link_attributes, but it didn’t work.

    Any help appreciated :]

  9. Martin, I had the same question. I tracked down the WordPress code. It turns out that WordPress applies the filters on the single post links a little differently. I’ve included some code below that works for those links. In can be used in conjunction with the code above.

    add_filter('next_post_link', 'post_link_attributes');
    add_filter('previous_post_link', 'post_link_attributes');
    
    function post_link_attributes($output) {
        $injection = 'class="styled-button"';
        return str_replace('<a href=', '<a '.$injection.' href=', $output);
    }
    
  10. Jason
    Permalink to comment#

    How can you add a class to “<a href" ather than "” for the wordpress menu as you would need to for implementations of fancybox?

  11. Jon
    Permalink to comment#

    How would i surround the link in a

    <

    div> so i could put it on its on bar, when i try putting it in a

    <

    div> it puts the div at the top of the page but the navigation itself stays after all the posts.

  12. Jack
    Permalink to comment#

    Thanks a lot for you help on this. I have successfully added a class to both, previous and next links.

    add_filter('next_posts_link_attributes', 'posts_link_attributes_1');
    add_filter('previous_posts_link_attributes', 'posts_link_attributes_2');
    
    function posts_link_attributes_1() {
        return 'class="prev_button" onclick="javascript:ajax_loadContent(\'box-right\',' . next_posts_link() . '");return false"';
    }
    
    function posts_link_attributes_2() {
        return 'class="next_button" onclick="javascript:ajax_loadContent(\'box-right\',' . previous_posts_link() . '");return false"';
    }
    

    However, as you can see I am having issues with using AJAX to load posts into my box-right DIV. I am using the following code to load links:

    <a href="#" onclick="javascript:ajax_loadContent('box-right','page.php');return false">hello</a>
    

    I am trying to use the previous_posts_link() function and put it where page.php is, in the code above. I cannot get it to work? I am quite new to PHP, so it may be simple?

    I wish to alter the return '<a href="' . previous_posts( false ) . "\" $attr>". preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label ) .'</a>'; code in the link-template.php file so that the href is a hash, href=#, and the $attr loads the onclick="javascript:ajax_loadContent('box-right','page.php');return false" – Whereby page.php actually uses a function to load the previous and next page.

    Please help me with this!
    Thanks!

    This is the approach I took, which did not work…

        return 'class="prev_button" onclick="javascript:ajax_loadContent(\'box-right\',' . previous_posts_link() . '");return false"';
    
  13. Thanks a lot for this information. The tip given by Justin works perfectly for my situation.

  14. Tony Mosley
    Permalink to comment#

    really having a hard time trying to add a filter onto these links in the head of the page

    I just want to add an ID of “pref” & “next” to be targeted by a simple page swipe but for some reason documentation on these links is hard to come by unless you want to remove them.

    can any one suggest a post or a snippet to create something like

  15. Tony Mosley
    Permalink to comment#

    this <link id="prev" rel='prev' title='Waiting' href='http://www.seventhsecond.com/waiting/' />

  16. Why would you wna do that when you already have:

    `post link[rel=”next”]{

    }`

    the only thing you need to make sure you have is you page/post class…

  17. ruben
    Permalink to comment#

    Looked around for a solution that would let me add a class from the template and wasn’t able to find one…. so I wrote this.

    “`
    /*
    Custom Function that modifies the standard previous/next link for single/index templates
    tested on : index.php , single.php
    */
    function prevnext__modify( $a , $attr = ” ){
    if(empty($a)) return;
    $_attr = ”;
    if(!empty( $attr ) && is_array($attr)):
    foreach($attr as $key => $val):
    $_attr[] = “{$key}=\”{$val}\””;
    endforeach;
    $_attr = join(‘ ‘, $_attr );
    endif;
    echo preg_replace(‘/( ‘button alignleft’,
    ));

    prevnext__modify( get_next_posts_link() ,
    $attributes = array(
    ‘class’ => ‘button alignright’,
    ));

    ////////////////////// /* SINGLE.php */

    prevnext__modify( get_previous_post_link( $format = “« %link”) ,
    $attributes = array(
    ‘class’ => ‘button’,
    ));

    prevnext__modify( get_next_post_link( $format = “%link »” ) ,
    $attributes = array(
    ‘class’ => ‘button’,
    ));
    “`

  18. LebCit
    Permalink to comment#

    Hello, thanks a lot !
    Justin Klemm method worked for me on previous/next posts links.
    If anyone wants to add a specific class to the previous/next comments links, here is the code

    add_filter(‘next_comments_link_attributes’, ‘comments_link_attributes’);
    add_filter(‘previous_comments_link_attributes’, ‘comments_link_attributes’);

    function comments_link_attributes() {
    return ‘class=”button success radius”‘;
    }

    Worked for me on WP 4.1
    THANKS AGAIN css-tricks !

  19. Permalink to comment#

    Hi guys. You may also look at get_adjacent_post function. It more flexible.
    Works great!

    http://codex.wordpress.org/Function_Reference/get_adjacent_post

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```