Displaying dynamic pages using with Rewriting rule and Query vars

This topic contains 0 replies, has 1 voice, and was last updated by  Caezar De Castro II 1 month, 2 weeks ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #9465

    WordPress can create a rewrite rule natively. We want to make use of that to listen for a specific slug and if that slug is existing on on the GET query. Our task to provide a page template for that page to render on the screen.

    But first, we need to make a new rewrite rule with the following scripts. In this script, we want to rule to slug called ‘custom’.

    function bytescrafter_rewrite_rules() {
        add_rewrite_rule( 'custom/([^/]+)/?$', 'index.php?custom=true', 'top' );
    }
    add_action('init', 'bytescrafter_rewrite_rules');

    Second, we need to register a query var on WordPress.

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

    Third, we just need to display a specific template for that previously created slug for the custom page.

    function bytescrafter_custom_template_include($template)
    {
        //Load $wp_query object
        global $wp_query;
        
        //Check if query var is set and equal to target permalink.
        $page_value = isset($wp_query->query_vars['category_name']) ? $wp_query->query_vars['category_name'] : true;
    
        //Check if page is our target page hence return.
        if ($page_value == "jesus") {
            return get_stylesheet_directory().'/templates/custom.php'; //set the target template.
        } else {
            return $template; //Load normal template fallback
        }
    }
    add_filter('template_include', 'bytescrafter_custom_template_include', 1, 1);

    Just take note that you can add this scripts on either your custom plugin or active theme’s function.php. For more WordPress codex tutorial, see Easiest way of having a site is WordPress for other WordPress codex tutorial.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic. Login here