3

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?

  • I'm not sure EP_PERMALINK works for page post type. There's a separate EP_PAGES mask. – Milo Sep 18 '15 at 4:12
  • @Milo I tried EP_PAGES and EP_ALL - I forget which one but one of them only showed the blog and the other showed the same 404 header. – Howdy_McGee Sep 18 '15 at 14:01
2

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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.