李建英 發表於 2023-7-22 00:00:00

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

<p>
经过两天的正则表达式的学习,和研究wordpress的路由函数,成功实现了自定义wordpress路由功能,以下是路由规则的实现。<br>
如果有自定义的url参数,要通过路由传递,必须通过wordpress的函数将参数添加进去:</p>
<p>
 </p>
<div>
<span><u>复制代码</u></span> 代码如下:</div>
<div id="code69988">
<br>
//add query_args<br>
function add_query_vars($aVars) {<br>
    $aVars[] = 'score';<br>
    $aVars[] = 'type'; // represents the name of the product category as shown in the URL<br>
    return $aVars;<br>
}<br>
add_filter('query_vars', 'add_query_vars');//wordpress过滤器</div>
<p>
 </p>
<p>
同时在获取参数的页面也要用到wordpress的函数获取:</p>
<p>
 </p>
<div>
<span><u>复制代码</u></span> 代码如下:</div>
<div id="code61702">
<br>
$type=isset($wp_query-&gt;query_vars['type'])?urldecode($wp_query-&gt;query_vars['type']):'';</div>
<p>
 </p>
<p>
 </p>
<div>
<span><u>复制代码</u></span> 代码如下:</div>
<div id="code39676">
<br>
//路由规则-根据时间排序以及各类别的最新条目<br>
function add_rewrite_rules($aRules) {<br>
    $aNewRules = array(<br>
        'text/([^latest][^/]+)/?(/page/(+)?)?/?$' =&gt; 'index.php?cat=2&amp;score=$matches&amp;paged=$matches',<br>
        'image/([^latest][^/]+)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=3&amp;score=$matches&amp;paged=$matches',<br>
        'video/([^latest][^/]+)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=4&amp;score=$matches&amp;paged=$matches',<br>
        'resource/([^latest][^/]+)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=5&amp;score=$matches&amp;paged=$matches',<br>
        'text/(latest)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=2&amp;type=$matches&amp;paged=$matches',<br>
        'image/(latest)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=3&amp;type=$matches&amp;paged=$matches',<br>
        'video/(latest)/?(/page/(+)?)?/?$'=&gt;'index.php?cat=4&amp;type=$matches&amp;paged=$matches',<br>
        'resource/(latest)/?$'=&gt;'index.php?cat=5&amp;type=$matches',<br>
        '(month)/?(/page/(+)?)?/?$'=&gt;'index.php?score=$matches&amp;paged=$matches',<br>
        '(24hr)/?(/page/(+)?)?/?$'=&gt;'index.php?score=$matches&amp;paged=$matches',<br>
    );<br>
    $aRules = $aNewRules + $aRules;<br>
    return $aRules;<br>
}<br>
add_filter('rewrite_rules_array', 'add_rewrite_rules');</div>
<p>
 </p>
<p>
 </p>
<div>
<span><u>复制代码</u></span> 代码如下:</div>
<div id="code79197">
<br>
//路由规则-类别<br>
add_rewrite_rule('^text/?(/page/(+)?)?/?$','index.php?cat=2&amp;paged=$matches','top'); //对应的类别ID<br>
add_rewrite_rule('^image/?(/page/(+)?)?/?$','index.php?cat=3&amp;paged=$matches','top');<br>
add_rewrite_rule('^video/?(/page/(+)?)?/?$','index.php?cat=4&amp;paged=$matches','top');<br>
add_rewrite_rule('^resource/?(/page/(+)?)?/?$','index.php?cat=5&amp;paged=$matches','top');</div>
<p>
 </p>
頁: [1]
查看完整版本: wordpress自定义url参数实现路由功能的代码示例