• Add custom rewrite rule and URL in WordPress

    Posted by markzero on Monday, July 2nd, 2012

    I’m not talking here about creating custom permalink structure after your pages (mysite.com/page/myrule/here), or posts, taxonomies or custom post types. No, I’m talking here about completely custom URL definition in your WordPress website (mysite.com/my/custom/structure) – without page as root parameter or any other WordPress type.

    Cliche – this is simple (when you get it on right track). Just add function to WordPress’ init function which will do all of the work. First, add rewrite rule using, you guess it, add_rewrite_rule function, so WP reacts on such URL. Next, add actual query variable into WP, using ordinary array_push method, so you can check when to display your own template (it can be plain text, or xml, or php/html…). Finally, filter template_redirect will do the trick to display your own template. Oh yes, and you need to flush your rules so WP actually use them.

     
    <?php
    add_action( 'init', array('My_Class','myclass_add_rewrite_rules' ));
     
    class My_Class {
    // ...
    public static function myclass_add_rewrite_rules() {
        add_rewrite_rule( '^myrule/(&#91;^/&#93;*)/?', 'index.php?myrule=$matches&#91;1&#93;', 'top' );
        add_filter('query_vars', array(__CLASS__, 'my_query_vars'), 1, 1);
        add_filter('template_redirect', array(__CLASS__, 'my_template_redirect'), 1, 0);
        global $wp_rewrite;
        $wp_rewrite->flush_rules(false);
    }
    // ...
    public static function my_query_vars($vars) {
        array_push($vars, 'myrule');
        return $vars;
    }
    // ...
    public static function my_template_redirect() {
        global $wp_query;
        if(isset($wp_query->query_vars["myrule"])) {
            $wp_query->is_404 = false; // maybe not needed
            $wp_query->is_feed = false; // maybe not needed
            ob_start();
            header('Content-Type: text/plain; charset=utf-8');
            // e.g. plain text here...
            ob_end_flush();
            exit;
        }
    }
    // ...
    }
    ?>

    Posted in: Wordpress.

    Share this story:

    Leave a Reply