I’m using add_rewrite_rule() to create a new endpoint to my author URL.

  • example.com/author/my-endpoint

Here’s my code:

// Pagination rule.
add_rewrite_rule( '^author/([^/]+)/my-endpoint/([0-9]+)/?$', 'index.php?author_name=$matches[1]&my-endpoint=1&pag=$matches[2]', 'top' );

// Endpoint rule.
add_rewrite_rule( '^author/([^/]+)/my-endpoint/?$', 'index.php?author_name=$matches[1]&my-endpoint=1', 'top' );

// Add query var.
add_filter( 'query_vars', function( $vars ) {
    $vars[] = 'my-endpoint';
    return $vars;
} );
// Template display.
add_filter( 'template_include', function( $template ) {
    global $wp_query;

    if ( is_404() ) {
        return $template;
    if ( array_key_exists( 'my-endpoint', $wp_query->query_vars ) ) {
        return trailingslashit( get_template_directory() ) . 'my-endpoint.php';
    return $template;
} );

I can now visit URLs such as:

  • example.com/author/my-endpoint/

…and also pagination such as:

  • example.com/author/my-endpoint/1/
  • example.com/author/my-endpoint/2/
  • example.com/author/my-endpoint/3/

My question

If my custom query (in my my-endpoint.php template) returns, say, 6 pages of results only, then how do I return a 404 for URLs such as the following?

  • example.com/author/my-endpoint/356/

Read more here: How to return a 404 when custom query matches nothing?


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: