“What I need is to have for example site.com/mypage/ but I do not want ‘mypage’ to exist in the backend.”
It’s a bit late, but maybe someone else is in a need for this as well:
Step 1
Create /templates/
folder inside your plugin, and create custom.php
file inside of it, with temporary content for testing purposes such as
<?php
echo "Hi";
Step 2
Add this code to your plugin:
add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ){
$wp_rewrite->rules = array_merge(
['mypage/?$' => 'index.php?custom=1'],
$wp_rewrite->rules
);
} );
add_filter( 'query_vars', function( $query_vars ){
$query_vars[] = 'custom';
return $query_vars;
} );
add_action( 'template_redirect', function(){
$custom = intval( get_query_var( 'custom' ) );
if ( $custom ) {
include plugin_dir_path( __FILE__ ) . 'templates/custom.php';
die;
}
} );
Please note that plugin_dir_path( __FILE__ )
may not be appropriate function for your case, depending on where you will add this code.
Step 3
Go to WP admin -> Settings -> Permalinks and re-save them, to flush/recreate permalinks.
Step 4
Try to visit yoursite.com/mypage
.
Clear your browser cache / history, or maybe even try incognito/different browser.
Step 5
Remove the testing code from custom.php
file and add your own backend code.