Add Unique Classes to Next and Previous in WP_LINK_PAGES

I’m using the below function for wp_link_pages. It can be viewed in use here.

I would like to add a class to the previous link and a class to the next link so they can be styled individually. I’m not a pro at WP functions and I’m curious what the proper way to do this is. I can always simply echo divs around each, but it seems there may be some better way to do this.

// WP_LINK_PAGES: Add prev and next links to a numbered link list
add_filter('wp_link_pages_args', 'wp_link_pages_args_prevnext_add'); 

function wp_link_pages_args_prevnext_add($args) { 
    global $page, $numpages, $more, $pagenow; 
    $args['before'] = '<div id="link_wrap">'; 
    $args['after'] = '</div>'; 
    $args['link_before'] = '<span class="classlinks">'; 
    $args['link_after'] = '</span>'; 
    if($page-1) // there is a previous page 
        $args['before'] .= ' '. _wp_link_page($page-1) . $args['link_before'] . $args['previouspagelink'] . $args['link_after'] . '</a>' . ' ' ; 
    if ($page<$numpages) // there is a next page 
        $args['after'] = ' '. _wp_link_page($page+1) . $args['link_before'] . $args['nextpagelink'] . $args['link_after'] . '</a></div>' ; 
    return $args; 
}

Related posts

Leave a Reply

2 comments

  1. First, I would add a string formatting placeholder to ‘link_before’, like so…

    $args['link_before'] = '<span class="classlinks %s">';
    

    Next, I would use sprintf() to insert an appropriate class for the appropriate link (let’s assume the classes will be ‘link-before’ and ‘link-after’, respectively). Like so…

    if($page-1) // there is a previous page 
        $args['before'] .= ' '. _wp_link_page($page-1) . sprintf($args['link_before'],'link-before') . $args['previouspagelink'] . $args['link_after'] . '</a>' . ' ' ; 
    
    if ($page<$numpages) // there is a next page 
        $args['after'] = ' '. _wp_link_page($page+1) . sprintf($args['link_before'],'link-after') . $args['nextpagelink'] . $args['link_after'] . '</a></div>' ; 
    
  2. You can do that either by means of JavaScript/jQuery, or you could use CSS selectors.

    The trick is to get the first and second <a> element inside the wrapper. Using CSS this would be something like #ID-OF-YOUR-WRAPPER a:firstchild { YOUR STYLE HERE }.