php - wordpress 插件开发 - 自定义URL的问题
PHP中文网
PHP中文网 2017-04-10 16:47:21
[PHP讨论组]
  1. 描述你的问题

我参考json-api这个插件的写法,想要自己实现一些数据接口,但是在自定义路由的时候一直不起作用。(我想自定义一个类似 '/api3/controlName' 这样的url接口)

  1. 贴上相关代码

<?php
/*
Plugin Name: My Plugin
Plugin URI: http://wordpress.org/plugins/my-plugin/
Description: A RESTful API for WordPress
Version: 1.1.1
Author: Dan Phiffer
Author URI: http://phiffer.org/
*/

$myPluginBase = 'api3';

function my_plugin_init() {
    global $wp_rewrite;
    add_filter('rewrite_rules_array', 'my_plugin_rewrites');
    add_action('template_redirect', 'my_plugin_template_rewrite');
    $wp_rewrite->flush_rules();
}

function my_plugin_template_rewrite(){
    global $myPluginBase;
    if( isset( $_REQUEST[ $myPluginBase ] ) ){
        echo $_REQUEST[ $myPluginBase ];
        exit;
    }
}

function my_plugin_activation() {
    // Add the rewrite rule on activation
    global $wp_rewrite;
    add_filter('rewrite_rules_array', 'my_plugin_rewrites');
    $wp_rewrite->flush_rules();
}

function my_plugin_deactivation() {
    // Remove the rewrite rule on deactivation
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

function my_plugin_rewrites($wp_rules) {
    global $myPluginBase;
    if (empty($base)) {
        return $wp_rules;
    }
    $my_plugin_rules = array(
        "$myPluginBase\$" => "index.php?{$myPluginBase}=info",
        "$myPluginBase/(.+)\$" => "index.php?{$myPluginBase}=\$matches[1]"
    );
    return array_merge($my_plugin_rules, $wp_rules);
}

// Add initialization and activation hooks
add_action('init', 'my_plugin_init');
register_activation_hook( __FILE__, 'my_plugin_activation');
register_deactivation_hook( __FILE__, 'my_plugin_deactivation');

?>

template_redirect这个action应该是生效了,比如访问 /api3=hello 能正常返回 hello,但是如果尝试访问 /api3/hello 则总是返回首页。

PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
PHP中文网

我的天哪,你的写的让我有点看不懂。
不过既然你提到你访问 /api3=hello可以正常返回hello 。首先请问它是一个什么类型的地址?

page?post?cat? 建议你先试试下面的代码

// 注册一个链接
add_action( 'init', 'api3_rewrites_init' );
function api3_rewrites_init(){
    add_rewrite_rule(
        'api3/(.+)\$',
        'index.php?&api3=$matches[1]',
        'top' 
    );
}

你的代码,我有一行不太了解

"$myPluginBase/(.+)\$" => "index.php?{$myPluginBase}=\$matches[1]"
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号