How to edit or override a Core function?

I want to add a data argument to links generated by the paginate_links() function. Then, I can more easily extend my custom pagination to use AJAX.

As far as I can tell, this function is not pluggable, nor does it have any hooks available.

The links generated by paginate_links() look like this:

<a class="page-numbers" href="https://example.com/list/page/2/"><span class="screen-reader-text">Page </span>2</a>

I want to add the data-page argument to the <a> tag so it looks like this:

<a data-page="2" class="page-numbers" href="https://example.com/list/page/2/"><span class="screen-reader-text">Page </span>2</a>

What would be the best way to edit a Core WordPress function that is not pluggable?

1 Answer
1

There is no filter, but you can set the type argument to array when you call paginate_links(), and then you can run a filter on the returned array.

Example:

$links = array_map(
    function( $link ) {
        if ( FALSE === strpos( $link, '/page/' ) )
            return str_replace( '<a ', '<a data-page="1" ', $link );

        return preg_replace(
            '~<a (.*)/page/(\d+)~',
            '<a data-page="\\2" \\1/page/\\2',
            $link
        );
    },
    paginate_links( [ 'type' => 'array' ] )
);

print join( ' | ', $links );

Leave a Comment