treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Add class to links generated by next_posts_link and previous_posts_link

Last updated on:

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

View Comments

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 :]

Leave a Comment

Use markdown or basic HTML and be nice.