Adding custom rewrite rules to WordPress

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:

Read More
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?

Related posts

Leave a Reply

2 comments

  1. 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);
    ?>