我想创建自定义url并从插件处理它
例如:-
domain.com/myplugin=endpoint&id=num&..
我只想返回json数据,不想返回模板谢谢
我想创建自定义url并从插件处理它
例如:-
domain.com/myplugin=endpoint&id=num&..
我只想返回json数据,不想返回模板谢谢
您只需要在将内容发送到浏览器之前调用一个处理程序函数。在不知道您想要做什么的情况下,下面是一个通用函数:
function my_plugin_json_handler(){
/*First you should check the POST/GET Request for some variable that tells
the plugin that this is a request for your json object*/
if(!isset($_REQUEST[\'my_triger\'] || $_REQUEST[\'my_trigger\'] !== \'some test value\')) return;
//generate your json here
echo $json; //echo your json to the browser
exit; //stop executing code (prevents the template from loading)
}
add_action(\'init\', \'my_plugin_json_handler\');
你到底要钓到哪里取决于你到底在做什么,但是init
通常是一个安全的地方。您可能还应该进行某种检查,以防止使用nonce
.根据您的需要,您还可以考虑ajax 打电话而不是检查$_REQUEST
在任意url上。
我是这样做的:
function custom_url_handler() {
$requestUri = $_SERVER["REQUEST_URI"];
$urlPattern = \'/^\\/([\\w\\d]*\\/)?index\\.php\\?my-trigger\\=1(\\&|$)/\';
preg_match($urlPattern, $requestUri, $matches);
if(count($matches) > 0){
$data = GetData();
wp_send_json($data);
}
}
add_action(\'parse_request\', \'custom_url_handler\');
这将返回$data
当您点击index.php?my-trigger=1
URL(后跟额外的URL参数,如index.php?my-trigger=1¶m1=4
, 或不)。当我从WPadmin创建或更新帖子时,我需要创建一个文件(任何类型:json、php、csv、txt)。格式结构为:ID,“要执行的操作”(新建帖子、更新帖子、删除帖子)、标题、字段2、字段3谢谢马丁