Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 771
dash Avatar asked Aug 31 '25 18:08

dash


1 Answers

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;
like image 136
bswatson Avatar answered Sep 02 '25 07:09

bswatson