1

Hope everyone is fine, I am learning custom endpoints in WordPress. I know how to create endpoints and how they work(a little bit). But I got stuck when I wanted to add an endpoint to only one page. Let me give you an example of what I want to do.

  1. A page named as example having id 77.
  2. Set a custom template to it like some-template.php
  3. If the user has set this template create endpoints like example.com/example/endpoint1 or example.com/example/endpoint2
  4. if the user opens another page like example.com/example-new/endpoint1, don't create an endpoint.

Here is the way I add endpoints.

add_action( 'init', 'add_new_e' );
add_filter( 'query_vars', 'filter_vars_e');
function add_new_e() {
    add_rewrite_endpoint( 'mash', EP_PAGES );
}

function filter_vars_e($vars) {
    $vars[] = 'mash';
    return $vars;
}

I am flushing rewrite rules when the plugin activates/deactivates.

Now the problem is when I open another page with an endpoint, it doesn't throw a 404 error, and I know that I am using the EP_PAGES mask.

Will someone help me with how I can achieve my goal.

Goal: add an endpoint to a specific page only having a specific template

Furthermore, I want to endpoints work in the same way as in woocommerce like my account page. Thanks in advance. If anybody needs other information please let me know.

1 Answer 1

2

No, add_rewrite_endpoint() doesn't limit to any specific page, only add_rewrite_rule() can do that.

However, if I understand it correctly, you can use the pre_handle_404 hook to check if the endpoint query is set and that the page uses a specific template, then throw a 404 error if those conditions are not met.

Working example based on your code:

add_filter( 'pre_handle_404', 'wpse_376370', 10, 2 );
function wpse_376370( $value, $wp_query ) {
    if (
        // It's a valid "mash" endpoint request,
        $wp_query->get( 'mash' )          &&
        // but the request is not a Page or its slug is not 'example',
        ! $wp_query->is_page( 'example' ) &&
        // and the Page is not using the template some-template.php.
        ! is_page_template( 'some-template.php' )
    ) {
        // Therefore, we throw a 404 error
        $wp_query->set_404();

        // and avoid redirect to the page. (at example.com/example)
        remove_action( 'template_redirect', 'redirect_canonical' );
    }

    return $value;
}
1
  • 1
    Thanks, @sallycj. I think this is the best solution for now. Commented Oct 14, 2020 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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