Skip to content

Instantly share code, notes, and snippets.

@iamfaisal
Last active November 27, 2017 21:00
Show Gist options
  • Save iamfaisal/12bd56f80428624658ff0d1daba83475 to your computer and use it in GitHub Desktop.
Save iamfaisal/12bd56f80428624658ff0d1daba83475 to your computer and use it in GitHub Desktop.
<?php
// rewrite rules
add_action('init', function () {
// show all pages under '/p/{pagename}'
global $wp_rewrite;
$wp_rewrite->page_structure = $wp_rewrite->root . 'p/%pagename%/';
// show all review pages under '/reviews/{pagename}'
add_rewrite_tag('%is_review%', '([^&]+)');
add_rewrite_rule('reviews/([^/]*)/?', 'index.php?pagename=$matches[1]&is_review=true', 'top');
flush_rewrite_rules();
}, 10, 0);
// handle redirection
add_action( 'template_redirect', function () {
global $post, $wp_query;
if (empty($wp_query->query_vars['is_review'])) return;
if (!is_page_template('page-review.php')) {
show404();
}
}, 1);
// update links in the backend for the pages that use a specific template
add_filter('page_link', function ($link, $post_id, $sample) {
if (get_page_template_slug($post_id) == 'page-review.php') {
return str_replace('/p/', '/reviews/', $link);
}
return $link;
}, 10, 3);
// execute 404
function show404() {
global $wp_query;
$wp_query->set_404();
status_header(404);
get_template_part(404);
exit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment