如何在 Wordpress 分页中添加 Class 到 Prev/Next? (paginate_links)

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

我修改了我的 Wordpress functions.php 以显示分页:

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

输出接近完美:

<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>

有没有办法将 class 添加到 PrevNext 列表项 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>

这是一个 javascript (jQuery) 的解决方案。不好,但它有效:

(function ( $ ) {
 
  $('ul.page-numbers li a').each(function() {
    var $this = $(this);
    if ( $this.hasClass('prev') ) $this.parent('li').addClass('prev-list-item');
    if ( $this.hasClass('next') ) $this.parent('li').addClass('next-list-item');      
  });
 
}( jQuery ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>

只需将 javascript 代码包裹在 <script></script> 标签中,然后将其插入 paginate_links() 函数之后。

您可以将链接列表作为数组返回,而不是直接输出函数。然后,您可以使用各自的功能定位下一个和上一个链接。

$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;