Custom Endpoint Gives 404 Header

I'm trying to write a general endpoint that loads a template. It works as expected with the small exception that the returned header is 404 - Page not Found. Am I missing something in my rewrites? Here's how the rewrite looks currently:

/** Register Query Vars **/
function theme_custom_query_vars( $vars ){
    $vars[] = 'map';
    return $vars;
}
add_filter( 'query_vars', 'theme_custom_query_vars' );

/** Register Endpoint **/
function theme_register_endpoints() {
    add_rewrite_endpoint( 'map', EP_PERMALINK );
}
add_action( 'init', 'theme_register_endpoints' );

/** Give Endpoint a Template **/
function endpoint_map_template( $templates = '' ){
    global $wp_query;

    if( ! ( isset( $wp_query->query['pagename'] ) && 'map' == $wp_query->query['pagename'] && ! is_singular() ) ) {
        return $templates;
    }

    include locate_template( 'page-templates/template-map.php', false, true );
    exit;

}
add_filter( 'template_redirect', 'endpoint_map_template' );

I've been looking around for a solution but everything says "Oh, just flush your rewrites!" but I've done that multiple times and played with the $wp_rewrite ( versus just saving permalinks with no avail. Can anyone point out what I'm missing or doing wrong?

Answers 1

  • I'm not sure if this is the only reason why it wasn't working but I was missing two things.

    1. I wasn't added any sort of rewrite rule to test on
    2. I was testing against pagename instead of query_vars.

    Here's the final solution:

    /** Register Query Vars **/
    function theme_custom_query_vars( $vars ){
        $vars[] = 'map';
        return $vars;
    }
    add_filter( 'query_vars', 'theme_custom_query_vars' );
    
    /** Register Endpoint **/
    function theme_register_endpoints() {
        add_rewrite_rule( '^map/?', 'index.php?map=map', 'top' );
        add_rewrite_endpoint( 'map', EP_PERMALINK );
    }
    add_action( 'init', 'theme_register_endpoints' );
    
    /** Give Endpoint a Template **/
    function endpoint_map_template( $templates = '' ){
        global $wp_query;
        $template = $wp_query->query_vars;
    
        if ( array_key_exists( 'map', $template ) && 'map' == $template['map'] ) {
            include( get_template_directory().'/page-templates/template-map.php' );
            exit;
        }
    }
    add_filter( 'template_redirect', 'endpoint_map_template' );
    

Related Questions