WordPress自定义URL重写 [英] Wordpress Custom URL Rewrites

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

问题描述

我的网站上有一些链接,这些链接将查询传递给从外部数据库查询的页面.效果很好,例如

I have links in my site that pass queries to pages that query from an external database. This works fine e.g.

mysite.com/catalog/?tl=flooring

但是我想重写此网址以显示为

however i want to rewrite this url to appear as

mysite.com/catalog/flooring

我曾尝试在wordpress中修改重写规则,但它始终显示索引页

Ive tried modifying the rewrite rules in wordpress but it always displays the index page

add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['(catalog)/([a-zA-Z0-9 ]+)$'] = '/catalog/?tl=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'id');
    return $vars;
}

推荐答案

WordPress中的重写规则并不像您期望的那样工作.所有重写规则都映射到文件处理程序(几乎总是index.php),而不是另一个URL.

Rewrite rules in WordPress don't quite work like how you're expecting them to. All rewrite rules map to a file handler (almost always index.php), not another URL.

这是一个简化的代码示例;

Here is a shortened code example;

$rules['catalog/(.*)/?'] = 'index.php?pagename=catalog&tl=$matches[1]';
array_push($query_vars, 'tl'); // note query var should match your query string

这会将catalog/whatever映射到WordPress页面'catalog',并传递查询var'tl'.您可以为目录"创建页面模板,然后使用get_query_var('tl')选择"tl"的值.

This would map catalog/whatever to the WordPress page 'catalog', and pass along the query var 'tl'. You could create a page template for 'catalog', then pick up the value of 'tl' using get_query_var('tl').

还要避免使用id这样的查询变量-使用更独特的内容(例如'tl')来避免与WordPress冲突.

Also avoid using query vars like id - use something more unique (like 'tl') to avoid clashes with WordPress.

并且不要在每次初始化时刷新规则!这是不好的做法,并且会写入.htaccess并在页加载时调用数据库更新!

And don't flush rules on every init! It's bad practice, and will write to .htaccess and call database updates on every page load!

只要您更新帖子或永久链接结构,WordPress就会始终刷新永久链接(只需在更改代码时更新永久链接).

WordPress will always flush permalinks whenever you update a post or your permalink structure (simply update your permalinks when you make changes to your code).

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

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