Add Class To Next Post and Previous Post Links

Home » Blog » WordPress Development » Add Class To Next Post and Previous Post Links

If you want to add a custom CSS class to the next post and previous post links, here’s an easy way to do so. You can simply add a filter function to the next_post_link and previous_post_link filters. This will let you add a custom class to these links.

Here’s the code to do so:

function add_custom_class_to_next_post_link($html){
    $html = str_replace('<a','<a class="next-post-link”',$html);
    return $html;
}
add_filter('next_post_link', 'add_custom_class_to_next_post_link',10,1);
 
function add_custom_class_to_previous_post_link($html){
    $html = str_replace('<a','<a class="previous-post-link"',$html);
    return $html;
}
add_filter('previous_post_link', 'add_custom_class_to_previous_post_link',10,1);

Add the above code to your functions.php file or put it in a custom plugin.

The above code first adds a filter function called add_custom_class_to_next_post_link to the next_post_link filter. That filter function will add a next-post-link CSS class to the next post link. The rest of the code does the same thing but for the previous post link.

Leave a Reply

Your email address will not be published. Required fields are marked *

Register an account to save your snippets or go Pro to get more features.