Adding custom rewrite rules to WordPress

2019-08-05 19:18发布

My WordPress site has a portfolio that is at www.mysite.com/portfolio/. The portfolio sections and items are administered through a custom plugin I created. I want to access the individual items like www.mysite.com/portfolio/my-cool-photo and have that put "my-cool-photo" into a query string like ?portfolio_item=my-cool-photo so I can read it from my code.

In the plugins activation PHP file I have this code:

function add_rewrite_rules($wp_rewrite) {
    $new_rules = array(
        'portfolio/(.+)/?$' => 'index.php?&portfolio_item=$1'
    );

    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');

function query_vars($public_query_vars) {
    $public_query_vars[] = "portfolio_item";

    return $public_query_vars;
}
add_filter('query_vars', 'query_vars');

This adds the rewrite rule to the array OK. The problem is it's not doing anything. When I go to www.mysite.com/portfolio/testing/ I get the "This is somewhat embarrassing, isn’t it?" WordPress 404 error page. Obviously the redirect isn't working, so the query string won't be filled, but just to make sure I did this:

global $wp_query, $wp_rewrite;
if ($wp_rewrite->using_permalinks()) {
    $searchKey = $wp_query->query_vars['portfolio_item'];
} else {
    $searchKey = $_GET['portfolio_item'];
}

...and sure enough the query string isn't getting passed.

Is there something I'm missing?

标签: wordpress
2条回答
一纸荒年 Trace。
2楼-- · 2019-08-05 19:27

Here is the example rewriting url code. Hopefully this will help users.

In this url like http://www.domainname.com/test-page?urltags=ABCD is run as http://www.domainname.com/test-page/ABCD

<?php
function add_my_rule() {    
    global $wp; 
    $wp->add_query_var('tags');
    add_rewrite_rule('test-page/([^/]*)','index.php?pagename=test-page&urltags=$matches[1]','top');
}
function add_my_tags() {
    add_rewrite_tag('%urltags%', '([^&]+)');
}
add_action('init', 'add_my_rule');
add_action('init', 'add_my_tags', 10, 0);
?>
查看更多
三岁会撩人
3楼-- · 2019-08-05 19:43

After you update the WordPress rewrite rules, you need to flush them:

http://codex.wordpress.org/Function_Reference/flush_rewrite_rules

You can choose to flush with the $hard parameter true, and then you should be able to see your rewrite rules in the .htaccess file.

查看更多
登录 后发表回答