WordPress将自定义url映射到一个函数

时间:2016-08-11 16:18:00

标签: php wordpress

我正在尝试将自定义网址结构添加到基于WordPress的网站。

例如:

example.com/machines             //list all machines in a table

example.com/machines?some=params //list filtered machines in a table

example.com/machines/1           //show single machine

数据将来自我已经开发的外部API,通过卷曲。

我无法将数据导入自定义帖子类型,因为它在许多表中进行了规范化,业务逻辑很复杂,而且其他设备也使用了api。

我查看了add_rewrite_rule的文档,但第二个参数让我感到难过:

$redirect
(string) (required) The URL you would like to actually fetch

好吧我没有要获取的url,我想运行一个函数,它将充当一个简单的路由器 - 获取url部分,调用外部api并返回一个包含正确数据的模板。

调用API会很简单,但是我如何将url实际路由到函数,以及我如何加载模板(利用现有的WordPress header.php和footer.php)让我感到难过。

2 个答案:

答案 0 :(得分:4)

经过大量谷歌搜索和阅读一些good resources后,我找到了解决方案。

第一步是使用add_rewrite_endpoint创建一个将映射到查询变量的基本URL:

add_action( 'init', function(){
    add_rewrite_endpoint( 'machines', EP_ROOT );
} );

在访问固定链接页面以刷新重写规则之后,下一步是挂钩操作'template_redirect'以在网址被点击时实际执行某些操作:

add_action( 'template_redirect', function(){
    if($machinesUrl = get_query_var('machines')){
        //var_dump($machinesUrl, $_GET);
        //$machinesURl contains the url part after example.com/machines
        //eg if url is example.com/machines/some/thing/else
        //then $machinesUrl == 'some/thing/else'
        //and params can be got at simply via $_GET
        //after parsing url and calling api, its just a matter of loading a template:
        locate_template( 'singe-machine.php', TRUE, TRUE );
        //then stop processing
        die();
    }
});

唯一能做到这一点的是处理对网址的点击,网址没有其他部分,例如example.com/machines。 事实证明,在某些方面,使用wordpresses guts,空字符串被评估为false并因此被跳过,因此最后一步是挂钩过滤器'request'并设置默认值:

add_filter( 'request', function($vars=[]){
    if(isset ( $vars['machines'] ) && empty ( $vars['machines'] )){
        $vars['machines'] = 'default';
    }
    return $vars;
});

这可以通过将所有内容包装在一个类中来轻松改进。 url解析和模板加载逻辑可以传递给基本的路由器,甚至是基本的MVC设置,从文件加载路由等,但上面是起点

答案 1 :(得分:2)

一个更简单的解决方案是仅创建一个新的模板重定向。

所以假设您加载了example.com/custom-url

/**
 * Process the requests that comes to custom url.
 */
function process_request() {
    // Check if we're on the correct url
    global $wp;
    $current_slug = add_query_arg( array(), $wp->request );
    if($current_slug !== 'custom-url') {
        return false;
    }

    // Check if it's a valid request.
    $nonce = filter_input(INPUT_GET, '_wpnonce', FILTER_SANITIZE_STRING);
    if ( ! wp_verify_nonce( $nonce,  'NONCE_KEY')) {
        die( __( 'Security check', 'textdomain' ) );
    }

    // Do your stuff here
    

    //
    die('Process completed' );
}
add_action( 'template_redirect', 'process_request', 0);