Firstly, I have tried several different suggestions from other stackoverflow users but I haven't had any luck.
I'm trying to build a kind of api from inside a plugin. The task is to let an external system call a URL within my plugin in order for it to initiate an internal procedure.
Currently I have a class which has a contructor. This is inside that constructor.
add_action( 'init', 'my_rewrite' );
function my_rewrite() {
global $wp_rewrite;
$plugin_url = plugins_url( 'my-api.php', __FILE__ );
$plugin_url = substr( $plugin_url, strlen( home_url() ) + 1 );
add_rewrite_rule('/my-api/(.*)', $plugin_url ,'top');
$wp_rewrite->flush_rules(true);
}
This then generates a RewriteRule in my htaccess file.
RewriteRule ^/my-api/(.*) /wp-content/plugins/my-api/classes/my-api.php [QSA,L]
Below is the whole .htaccess file for context
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^/slurp-api/(.*) /wp-content/plugins/slurp/classes/my-api.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
For whatever reason when I visit site.dev/my-api I see a 404 page rather than the echo statement that should run from my-api.php
The dev site is being run through mamp pro if that is any help.
Any pointers as to why this rewrite isn't playing fair would be greatly appreciated.
Thanks
So, after much tinkering I came upon the correct answer. I changed this line to
add_rewrite_rule('my-api', $plugin_url ,'top');
I tried many variations on this but this one finally worked. Thanks for the help.
Remove the leading forward slash from the original request
RewriteRule ^my-api/(.*) /wp-content/plugins/my-api/classes/my-api.php [QSA,L]
And make sure the file my-api.php
exists at the location you give in the rewrite target:
/wp-content/plugins/my-api/classes/my-api.php
So as not to intentionally give it a non-existent target.
As @Starkeen mentions in the comments, you can remove the leading forward slash from the target also, like this
RewriteRule ^my-api/(.*) wp-content/plugins/my-api/classes/my-api.php [QSA,L]