WordPress custom post type rewrite rule

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:

Read More

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.

Related posts

1 comment

  1. 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.

Comments are closed.