Custom Rewriting to Plugin with Parameters

This approach should work for you:

<?php
/**
 * Plugin Name: Rewrite Shortcode
 **/

 add_shortcode( 'myplugin', 'mp_shortcode' );
 function mp_shortcode(){
    return '<p>Filter: ' . get_query_var( 'filter' ) . '</p>';
 }

 add_action( 'init', 'mp_rewrite' );
 function mp_rewrite(){
    $post_id = 2;
    add_rewrite_rule( 'myplugin/([^/]+)/?$', 'index.php?p=' . $post_id . '&filter=$matches[1]', 'top' );
    add_rewrite_tag( '%filter%', '([^/]+)' );
 }
?>

I developed it quickly as a small plugin, so I was able to test it myself. While you work with the global $wp_rewrite I thought it might be better to use the functions, which are documented in the Codex. Basically just, because I know them better 🙂 So I can’t exaktly tell, what you did wrong, but I can tell, what I do differently.

You’re approach:

"myplugin/([^/]+)/?" => "?p=2&filter=$matches[1]

I’ve explicitly told WordPress to use the index.php as it is also done in the documents. And I use add_rewrite_tag() to generate a new query variable, which I can read with get_query_var() in my shortcode.

Attention: Flush the Rules!
When you use these functions, you have to go to Settings > Permalinks and click the “update”-button. If you don’t do this, the new rules won’t be active. You could also use flush_rewrite_rules() during the activation of the plugin. An example on how to do this is given in the Codex.

Docs:

Leave a Comment