Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

The site that I am working on uses the following "pretty" permalink structure:

http://example.com/blog/my-special-post

But for a custom post type my client would like to avoid having a "pretty" slug:

http://example.com/product/142

How can the post ID be used in place of the slug for the custom post type?

I believe that this might be possible using WP_Rewrite, but I do not know where to begin.

share|improve this question

1 Answer 1

up vote 14 down vote accepted

This is what I use to rewrite custom post type URLs with the post ID. You need a rewrite rule to translate URL requests, as well as a filter on post_type_link to return the correct URLs for any calls to get_post_permalink():

add_filter('post_type_link', 'wpse33551_post_type_link', 1, 3);

function wpse33551_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'product' ){
        return home_url( 'product/' . $post->ID );
    } else {
        return $link;
    }
}

add_action( 'init', 'wpse33551_rewrites_init' );

function wpse33551_rewrites_init(){
    add_rewrite_rule(
        'product/([0-9]+)?$',
        'index.php?post_type=product&p=$matches[1]',
        'top' );
}
share|improve this answer
    
Excellent stuff, thanks! –  Lea Hayes Nov 12 '11 at 3:09

protected by Community Nov 23 '12 at 19:02

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.