How to customize get_the_post_navigation in theme

get_the_post_navigation() function is defined inside wp-includes/link-template.php

How can I override it in my theme?

Related posts

Leave a Reply

1 comment

  1. get_the_post_navigation does not utilize any filters so there is no easy way to modify or override all of its output.

    While get_the_post_navigation does not apply any filter itself, it does call functions that do apply filter. Specifically get_adjacent_post_link:

    return apply_filters( "{$adjacent}_post_link", $output, $format, $link, $post );
    

    Hooking into that filter will allow you to override some, but not all, of the output. get_the_post_navigation also uses _navigation_markup which does not apply any filters. That portion of the output cannot be overridden.

    You could request that a filter be added to that function. It would be a simple update and it would enable you to override all of the output.

    function _navigation_markup( $links, $class = 'posts-navigation', $screen_reader_text = '' ) {
        if ( empty( $screen_reader_text ) ) {
            $screen_reader_text = __( 'Posts navigation' );
        }
    
        $template = '
        <nav class="navigation %1$s" role="navigation">
            <h2 class="screen-reader-text">%2$s</h2>
            <div class="nav-links">%3$s</div>
        </nav>';
    
        //Add this line
        $template = apply_filters('navigation_markup_template', $template);
    
        return sprintf( $template, sanitize_html_class( $class ), esc_html( $screen_reader_text ), $links );
    }
    

    An easier solution might just be to create your own post navigation function, and then replace all references to get_the_post_navigation in your theme with your function.