2016-10-28 57 views
0

我是新插件wordpress。我有問題訪問WordPress插件的正確方法是什麼?比方說,在我的插件中,我需要創建端點來處理不同的回調。我已經嘗試了許多搜索結果,但不起作用。我不知道什麼是錯的。請幫忙。如何使用URL重寫規則來處理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

好,我找到了回答。

<?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'); 

訪問來自瀏覽器的URL

接受參數=通知或返回

http://localhost:8080/wordpress/callback.php?callback=notify 通知URL

http://localhost:8080/wordpress/callback.php?callback=something 404無效的端點