Select Page

Adding CSS classes to your next and previous post links is a great way to style your WordPress posts. By default, WordPress will output next and previous post links with the anchor tags. However, you can add CSS classes to these links to style them however you like.

In this article, we will show you how to add CSS classes to your next and previous post links.

Add this code to your functions.php file or a custom plugin file:

function add_custom_class_next_post_link($html){
    $html = str_replace('<a', '<a class="custom-next-link"', $html);
    return $html;
}
add_filter('next_post_link', 'add_custom_class_next_post_link', 10, 1);
 
function add_custom_class_previous_post_link($html){
    $html = str_replace('<a', '<a class="custom-prev-link"', $html);
    return $html;
}
add_filter('previous_post_link', 'add_custom_class_previous_post_link', 10, 1);

The above code adds a custom class to the next and previous post links. This can be useful for styling the links using CSS. The code adds custom classes to the next and previous links by hooking into the filters for next_post_link and previous_post_link respectively.