Search code examples
wordpressurl-rewritingpermalinks

Wordpress - Rewrite from ?demo to /demo/


Problem

I want to rewrite my GET-variable to /demo/.

My current permalink structure:
/my-new-post/?demo=true

What I want:
/my-new-post/demo/

I have this code:

It allows the "demo" $_GET variable and then echo "true". It works, just the rewrite part left.

<?php
add_filter('query_vars', 'queryvars' );
add_action('parse_query', 'echo_query_var');

function queryvars( $qvars )
{
    $qvars[] = 'demo';
    return $qvars;
}

function echo_query_var() {
    echo get_query_var('demo');
}
?>

Additional information

  • It should work with all posts (not just "my-new-post").
  • It should not return 404.
  • I should be able to get the post ID.
  • GET variable "demo" can be true, or empty. Not important.

Solution

  • This works so far...

    // Actions - Rewrite rules
    add_filter('query_vars', array($wp_comment_pages, 'add_get_variable'));
    add_action('generate_rewrite_rules', array($wp_comment_pages, 'add_rewrite_rule'));
    
    // Plugin container
    class wp_comment_pages
    {   
        // Flush the rules - only needed once
        function flush_rules()
        {
            global $wp_rewrite;
            $wp_rewrite->flush_rules();
        }
    
        // Add get variable to query vars
        function add_get_variable($public_query_vars)
        {
            $public_query_vars[] = 'demo';
            return $public_query_vars;
        }
    
        // Generate permalinks
        function add_rewrite_rule($wp_rewrite)
        {
            $new_rules = array(
                '(.+)/demo' => 'index.php?p=' . $wp_rewrite->preg_index(1) . '&demo=true'
            );
    
            $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
        }
    }