WordPress: Custom Rewrite URL To Call Plugin Function

Here is an example code snippet to show how you can access your plugin via a custom (rewrite) URL. In the example below, a request to http://example.com/blog/example/some-var/([0-9]+)/?$ will eventually execute the function my_plugin_template_redirect_intercept() in our plugin file, where you can add your custom code.

add_action( 'template_redirect', 'my_plugin_template_redirect_intercept' );
function my_plugin_template_redirect_intercept() {
	global $wp_query;
	if( $wp_query->get('my-plugin') ) {
		$someVar = $wp_query->get('some-var');
		// do stuff
		exit;
	}
}

function my_plugin_add_rewrite_rules() {
	$rule = '^/blog/example/some-var/([0-9]+)/?$';
	add_rewrite_rule(
		$rule,
		'index.php?my-plugin=1&some-var=$matches[1]',
		'top' );
}

add_action( 'init', 'my_plugin_rewrites_init' );
function my_plugin_rewrites_init() {
	add_rewrite_tag( '%my-plugin%', '([0-9]+)' );
	add_rewrite_tag( '%post-id%', '([0-9]+)' );
	my_plugin_add_rewrite_rules();
}

register_activation_hook( __FILE__, 'my_plugin_activate' );
function my_plugin_activate() {
	global $wp_rewrite;
	my_plugin_add_rewrite_rules();
	$wp_rewrite->flush_rules();
}

Some explanations:

  • Whenever you add a new rewrite rule, you have to call $wp_rewrite->flush_rules() . This function is said to be very expensive in resources, that’s why we want to execute it only once: an idea would be to call it once during the plugin activation.
     
  • http://codex.wordpress.org/Rewrite_API/add_rewrite_tag#Retrieving_the_Value_of_a_Rewritten_URL
    « Note that using $_GET on a rewritten URL will not work, even if the rewrite includes the querystring variables. You must use $wp_query. »
     
  • The template_redirect hook will be called right before WP determines which template page to load (and thus before any page output), which makes it the perfect hook for custom output, redirecting the user to other pages based on e.g. user permissions, or choosing a template on the fly based on user settings, mobile detection, …

Post a Comment