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;
}