Custom Page URL Rewrite WordPress

WordPress has self hooks to rewrite custom page. These hooks we can use in plugin or functions.php which is under themes folder. I am going to define you how to create rewrite URL for custom page.

objective:

  1. Add a rewrite rule on a custom post type permalink
  2. Use a page template based on the rewrite rule

First Define the rewrite the rule as “view-venue/?slug=abcd”.

// Create the rewrites
function userpage_rewrite_rule() {
add_rewrite_tag( '%venues%', '([^&]+)' );
add_rewrite_rule(
'^venues/([^/]*)/?',
'index.php?venues=$matches[1]',
'top'
);
}
add_action('init','userpage_rewrite_rule'); //Admin initialize code to add rewrite url

Second get the vars which are coming look code below


function userpage_rewrite_add_var( $vars ) {
$vars[] = 'venues';
return $vars;
}
add_filter( 'query_vars', 'userpage_rewrite_add_var' );

Final Step

Now connect the template page to URL and write the code to fetch detail and show.


// Catch the URL and redirect it to a template file
function userpage_rewrite_catch() {
global $wp_query;

if ( array_key_exists( 'venues', $wp_query->query_vars ) ) {
include (TEMPLATEPATH . '/view-venue.php');
exit;
}
}
add_action( 'template_redirect', 'userpage_rewrite_catch' );

function userpage_rewrite() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action('init','userpage_rewrite');

For any other help please click on contact Us.

Leave a Comment

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