我是wordpress插件的新手。我有问题,访问wordpress插件的正确方法是什么?让我们说在我的插件中,我需要创建端点来处理不同的回调。我尝试了很多谷歌搜索结果,但没有工作。我不知道出了什么问题。请帮忙。
<?php
/*
Plugin Name: MyPlugin
Description: MyPlugin
Author: Myself
Author URI:
Version: 1.0
License:
License URI:
*/
class MyPlugin {
private static $instance;
public static function getInstance() {
if(self::$instance == NULL) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action( 'init', array($this, 'set_endpoint' ) );
}
function set_endpoint() {
add_rewrite_rule( 'callback/$', plugin_dir_url(__FILE__) . 'callback.php', 'top' );
}
static function activate() {
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
}
MyPlugin::getInstance();
register_deactivation_hook(__FILE__,'flush_rewrite_rules');
register_activation_hook(__FILE__,'MyPlugin::activate');
callback.php
<?php echo '<h1> Hello </h1>'; ?>
答案 0 :(得分:1)
好的,我找到了答案。
<?php
class MyPlugin {
private static $instance;
public static function getInstance() {
if(self::$instance == NULL) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action( 'init', array($this,'callback_init_internal' ) );
add_filter( 'query_vars', array($this,'callback_query_vars' ) );
add_action( 'parse_request', array($this,'callback_request' ) );
}
function callback_init_internal()
{
add_rewrite_rule( 'callback.php', plugin_dir_url(__FILE__) . 'callback.php?callback=$matches[1]', 'top' );
}
function callback_query_vars( $query_vars )
{
$query_vars[] = 'callback';
return $query_vars;
}
function callback_request( &$wp )
{
if ( array_key_exists( 'callback', $wp->query_vars ) ) {
header('content-type: text/html; charset=utf-8');
$value = $wp->query_vars['callback'];
if ( $value === 'return' ) {
echo 'Return URL';
} else if ( $value === 'notify' ) {
echo 'Notify URL';
} else {
echo '404 Invalid endpoint';
}
exit();
}
return;
}
static function activate() {
global $wp_rewrite;
flush_rewrite_rules();
$wp_rewrite->flush_rules(true);
}
}
MyPlugin::getInstance();
register_deactivation_hook(__FILE__,'flush_rewrite_rules');
register_activation_hook(__FILE__,'MyPlugin::activate');
从浏览器访问网址
接受的参数=通知或返回
http://localhost:8080/wordpress/callback.php?callback=notify 通知网址
http://localhost:8080/wordpress/callback.php?callback=something 404无效端点
答案 1 :(得分:0)
您可以使用此插件获得更易读且更简单的方法,https://github.com/jbrinley/WP-Router
此博客可能有所帮助,https://www.pmg.com/blog/a-mostly-complete-guide-to-the-wordpress-rewrite-api/