Wordpress add rewrite rule to point to plugin file

自闭症网瘾萝莉.ら 提交于 2020-01-03 04:36:07

问题


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


回答1:


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]



回答2:


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.



来源:https://stackoverflow.com/questions/34156268/wordpress-add-rewrite-rule-to-point-to-plugin-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!