WordPress自定义URL路由 [英] Wordpress Custom Url Routing

查看:1129
本文介绍了WordPress自定义URL路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求所有url的末尾都有一个变量,并且都解析为相同的控制器/视图

I have a requirement that all urls have a variable at the end and all resolve to the same controller/view

例如,我们有以下URL:

so for example we have the following URL's:

http://example.com/users/joe
http://example.com/users/sam
http://example.com/users/jack

所有三个URL都应解析为

All three URLS should resolve to the same controller, where I would apply some logic to render each page differently based on the username.

如何在Wordpress上实现这种类型的路由?

How can I achieve this type of routing on Wordpress?

推荐答案

您可以对此进行重写...链接到最后一个函数中的控制器文件,然后从那里调用视图。

you can use a rewrite for this...link to your controller file in the last function and call the view from there.

不要忘记访问永久链接页面并保存(这将刷新重写规则)。

dont forget to visit the permalinks page and save (this flushes the rewrite rules).

    add_action('init', 'anew_rewrite_rule');
    function anew_rewrite_rule(){
       add_rewrite_rule('^users\\/[a-z]','index.php?is_customusers_page=1','top');  
    }

    add_action('query_vars','controller_set_query_var');
    function controller_set_query_var($vars) {
        array_push($vars, 'is_customusers_page'); // ref url redirected to in add rewrite rule

        return $vars;
    }


    //we'll call it a template but point to your controller
    add_filter('template_include', 'include_controller');
    function include_controller($template){


        // see above 2 functions..
        if(get_query_var('is_customusers_page')){
            //path to your template file
            $new_template = get_stylesheet_directory().'/controllerpath.php';
            if(file_exists($new_template)){
                $template = $new_template;
            } 
        }    

        return $template;    

    }

这篇关于WordPress自定义URL路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆