I’m using this code to create a rewrite endpoint in a custom plugin:

function setup_seo_endpoing() {
    add_rewrite_endpoint( 'item', EP_ALL );
}

add_action( 'init', 'setup_seo_endpoint');

This code is running / getting called, and the endpoint works with one problem:

If I visit the home page (let’s say http://example.com), it is in fact displaying the correct static page per dashboard settings.

If I attempt to visit the home page with the custom endpoint set (such as http://example.com/item/ct588), WordPress displays the blog listing.

For completeness, the below code is what I’m using (inside of a function) to get the value from the endpoint.

global $wp_query;
if ( isset( $wp_query->query_vars[ 'item' ] ) ) {
    // ... do stuff
    // This does not fire
}

Relevant notes:

  1. I’ve set the Settings => Reading => Front Page setting to be a static page.
  2. I’ve set the Settings => Reading => Blog page setting to a different page.
  3. The rewrite rules / query_var do work properly on inner page urls: http://example.com/sample-page/item/ct0608/
  4. I’ve saved permalinks multiple times

Why does the blog listing get displayed instead of the static home page?

Is it possible to use custom rewrite endpoints on the home page? No article I’ve found actually indicates this would / could work on the home page.

1 Answer
1

You’ll need to use a combination of add_rewrite_tag and add_rewrite_rule

function setup_seo_endpoint() {
    // Ensures the $query_vars['item'] is available
    add_rewrite_tag( '%item%', '([^&]+)' );

    // Requires flushing endpoints whenever the 
    // front page is switched to a different page
    $page_on_front = get_option( 'page_on_front' );

    // Match the front page and pass item value as a query var.
    add_rewrite_rule( '^item/([^/]*)/?', 'index.php?page_id='.$page_on_front.'&item=$matches[1]', 'top' );
    // Match non-front page pages.
    add_rewrite_rule( '^(.*)/item/([^/]*)/?', 'index.php?pagename=$matches[1]&static=true&item=$matches[2]', 'top' );
}
add_action( 'init', 'setup_seo_endpoint', 1);

// http://wordpress.stackexchange.com/a/220484/52463
// In order to keep WordPress from forcing a redirect to the canonical
// home page, the redirect needs to be disabled.
function disable_canonical_redirect_for_front_page( $redirect ) {
    if ( is_page() && $front_page = get_option( 'page_on_front' ) ) {
        if ( is_page( $front_page ) ) {
            $redirect = false;
        }
    }

    return $redirect;
}
add_filter( 'redirect_canonical', 'disable_canonical_redirect_for_front_page' );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *