• 技术文章 >后端开发 >php教程

    wordpress自定义url参数实现路由功能的代码示例_php实例

    2016-06-07 17:22:56原创379
    经过两天的正则表达式的学习,和研究wordpress的路由函数,成功实现了自定义wordpress路由功能,以下是路由规则的实现。
    如果有自定义的url参数,要通过路由传递,必须通过wordpress的函数将参数添加进去:

    复制代码 代码如下:

    //add query_args
    function add_query_vars($aVars) {
    $aVars[] = 'score';
    $aVars[] = 'type'; // represents the name of the product category as shown in the URL
    return $aVars;
    }
    add_filter('query_vars', 'add_query_vars');//wordpress过滤器

    同时在获取参数的页面也要用到wordpress的函数获取:

    复制代码 代码如下:

    $type=isset($wp_query->query_vars['type'])?urldecode($wp_query->query_vars['type']):'';

    复制代码 代码如下:

    //路由规则-根据时间排序以及各类别的最新条目
    function add_rewrite_rules($aRules) {
    $aNewRules = array(
    'text/([^latest][^/]+)/?(/page/([0-9]+)?)?/?$' => 'index.php?cat=2&score=$matches[1]&paged=$matches[3]',
    'image/([^latest][^/]+)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=3&score=$matches[1]&paged=$matches[3]',
    'video/([^latest][^/]+)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=4&score=$matches[1]&paged=$matches[3]',
    'resource/([^latest][^/]+)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=5&score=$matches[1]&paged=$matches[3]',
    'text/(latest)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=2&type=$matches[1]&paged=$matches[3]',
    'image/(latest)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=3&type=$matches[1]&paged=$matches[3]',
    'video/(latest)/?(/page/([0-9]+)?)?/?$'=>'index.php?cat=4&type=$matches[1]&paged=$matches[3]',
    'resource/(latest)/?$'=>'index.php?cat=5&type=$matches[1]',
    '(month)/?(/page/([0-9]+)?)?/?$'=>'index.php?score=$matches[1]&paged=$matches[3]',
    '(24hr)/?(/page/([0-9]+)?)?/?$'=>'index.php?score=$matches[1]&paged=$matches[3]',
    );
    $aRules = $aNewRules + $aRules;
    return $aRules;
    }
    add_filter('rewrite_rules_array', 'add_rewrite_rules');

    复制代码 代码如下:

    //路由规则-类别
    add_rewrite_rule('^text/?(/page/([0-9]+)?)?/?$','index.php?cat=2&paged=$matches[2]','top'); //对应的类别ID
    add_rewrite_rule('^image/?(/page/([0-9]+)?)?/?$','index.php?cat=3&paged=$matches[2]','top');
    add_rewrite_rule('^video/?(/page/([0-9]+)?)?/?$','index.php?cat=4&paged=$matches[2]','top');
    add_rewrite_rule('^resource/?(/page/([0-9]+)?)?/?$','index.php?cat=5&paged=$matches[2]','top');

    php入门到就业线上直播课:查看学习

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    自己动手写 PHP MVC 框架:点击学习

    快速了解MVC架构、了解框架底层运行原理

    上一篇:php用header函数实现301跳转代码实例_php实例 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• 你知道如何用PHP实现多进程吗• php里 的 四舍五入_PHP教程• PHP中全面阻止SQL注入式攻击分析小结_PHP教程• 第八节 访问方式 [8]_PHP教程• 使用阿里云低成本打造站内搜索引擎
    1/1

    PHP中文网