How To Add a Class to Prev/Next on Wordpress Pagination? (paginate_links)

10,815

Instead of having the function output directly, you could have the list of links returned as an array. You can then target the next and previous links with their own respective functions.

$links = paginate_links( array(
  'prev_next'          => false,
  'type'               => 'array'
) );

if ( $links ) :

    echo '<ul class="page-numbers">';

    // get_previous_posts_link will return a string or void if no link is set.
    if ( $prev_posts_link = get_previous_posts_link( __( 'Previous Page' ) ) ) :
        echo '<li class="prev-list-item">';
        echo $prev_posts_link;
        echo '</li>';
    endif;

    echo '<li>';
    echo join( '</li><li>', $links );
    echo '</li>';

    // get_next_posts_link will return a string or void if no link is set.
    if ( $next_posts_link = get_next_posts_link( __( 'Next Page' ) ) ) :
        echo '<li class="next-list-item">';
        echo $next_posts_link;
        echo '</li>';
    endif;
    echo '</ul>';
endif;
Share:
10,815
dash
Author by

dash

Updated on June 04, 2022

Comments

  • dash
    dash almost 2 years

    I modified my Wordpress functions.php to show a pagination:

    <?php echo paginate_links( array(
        'prev_text'          => __('Previous Page'),
        'next_text'          => __('Next Page'),
        'type'               => 'list'
    ) ); ?>
    

    The output is nearly perfect:

    <ul class="page-numbers">
        <li>
            <span class="page-numbers current">1</span>
        </li>
        <li>
            <a class="page-numbers" href="https://domain.tld/page/2/">2</a>
        </li>
        …
        <li>
            <a class="page-numbers" href="https://domain.tld/page/10/">10</a>
        </li>
        <li>
            <a class="next page-numbers" href="https://domain.tld/page/2/">Next Page</a>
        </li>
    </ul>
    

    Is there a way to add a class to the Prev and Next list item li?

        <li class="prev-list-item">
            <a class="prev page-numbers" href="http://domain.tld/page/1/">Previous Page</a>
        </li>
    

    &

        <li class="next-list-item">
            <a class="next page-numbers" href="http://domain.tld/page/2/">Next Page</a>
        </li>
    
  • dash
    dash over 7 years
    This solution works like a charm. Thank you very much.
  • dash
    dash over 7 years
    As I try to avoid JavaScript where possible and do not have jQuery implemented, this solution does not meet my needs. Thanks for your reply anyway.
  • Andy Tschiersch
    Andy Tschiersch over 7 years
    You can try type: 'array' - Returns an array of the paginated link list to offer full control of display. (Oops, this solution is used in the accepted answer, not seen )