1
votes

I'm trying to add a rule for a custom post type. By default, the URL to view post is www.mydomain.com/job/post-slug

What I'd like, is the post also accessible with the following URL:

www.mydomain.com/j/postid

I've tried this in my functions.php file and I also refresh permalinks in admin settings:

function rewrite_short_job_url() {

    add_rewrite_rule( '^j/([0-9]+)/?', 'index.php?post_type=job&id=$matches[1]', 'top' );
    flush_rewrite_rules( true );

}

add_action( 'init', 'rewrite_short_job_url' );

Doesn't work for me, I'm trying to understand the Rewrite API but cannot find a solution.

1
I'm not sure that you should be flushing rewrite rules during each request...Also, have you tested your redirect manually? What happens when you go to: index.php?post_type=job&id=15 (or some other ID)? You may need to use page_id. - rnevius
Ok got it, I was wrong in the redirect url, it's index.php?p=xxx that's all. Thanks - Fredmat

1 Answers

2
votes

I believe you should be using the following:

function rewrite_short_job_url() {
    add_rewrite_rule( '^j/([0-9]+)/?', 'index.php?post_type=job&p=$matches[1]', 'top' );
}
add_action( 'init', 'rewrite_short_job_url' );

It's important to keep the post_type var, so that only job posts use that redirect.

You can view a list of WordPress query variables in the Codex.