I need add a rewrite rule in my plugin, and distribute it with my code. All works fine if I put the rule in the .htaccess in the WordPress root folder, but I need distribute the plugin with my rule.
I try to put a .htaccess inside the plugin folder and try to use the add_rewrite_rule function but doesn't works either.
Here the .htaccess code that works correctly in WordPress root folder but doesn't works in my plugin folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule my-plugin/pages/tp(.*)\.php$ wp-content/plugins/my-plugin/pages/request.php?pid=$1
</IfModule>
I try the follow code in my plugin but doesn't works either:
add_filter( 'query_vars', 'add_query_vars' );
function add_query_vars( $query_vars )
{
$query_vars[] = 'pid';
return $query_vars;
}
add_action( 'init', 'add_init' );
function add_init()
{
$plugin_url = 'the-path-to-my-plugin-folder';
add_rewrite_rule('my-plugin/pages/tp(.*)\.php'
, $plugin_url . 'pages/request.php?pid=$matches[1]','top');
global $wp_rewrite;
$wp_rewrite->flush_rewrite_rules(); // I know this should be called only one time, but I put it here just to keep simple the sample code
}
But I always get the error that the URL wasn't found. What I'm doing wrong? How can I do what I need? I searched for similar questions but none solve my problem.
My plugin folder structure is:
Main folder: /wp-content/plugins/my-plugin ------ /pages (sub folder) -------------/request.php (script that should receive the request)
WP handles the plugins from the
/wp-admin
directory with a PHP script (admin.php), like this:Therefore, .htaccess files in the plugin directory are not parsed when the plugin is called. They have to be placed in the
wp-admin
directory or in the root directory, as you already found out.Although copying the .htacces file to the root directory when the plugin is installed -and deleting it when it is removed- is possible, I don't think it is the best option. Having .htaccess files in the WP space doesn't seem like a good idea.
Your second approach looks much better: Creating rewrite rules in the main script.
Looking at your code, I think the problem are the pattern (Incoming URL string to match) and possibly the substitution URL path ($plugin_url in your question).
The
$rule
parameter in theadd_rewrite_rule()
function should capture a segment of the URL (Above) used to call the plugin's modules.I can't suggest anything else because you don't supply enough information about the plugin and it's directory tree, except what can be guessed from the regex in the rewrite rule. But, this is a general idea of a way to achieve what you need.
The issue is in the second parameter of you
add_rewrite_rule
function call. It has to start fromindex.php?
and then there should be your arguments, likepid
, for example:So your
add_init
function should be like this:Don't forget to flush rewrite rules by visiting
Settings
»Permalinks
page.Further reading: