8

I'm registering my CPT like so:

$args = array(
    'labels' => $labels,
    'public' => true,
    'hierarchical' => false,
    'rewrite' => array(
        'with_front' => false,
        'slug' => 'news/events'
    ),
    'supports' => array( 'title', 'editor', 'thumbnail' )
);
register_post_type('events',$args);

Now that will generate post permalinks like so: /news/events/{post_name}/ but I want the following permalink structure: /news/events/{post_id}/{post_name}/.

How do I do this?

2 Answers 2

9

@Bainternet - your answer didn't fully work but I did some more searching and was able to piece this filter together that did work:

add_filter('post_type_link', 'custom_event_permalink', 1, 3);
function custom_event_permalink($post_link, $id = 0, $leavename) {
    if ( strpos('%event_id%', $post_link) === 'FALSE' ) {
        return $post_link;
    }
    $post = &get_post($id);
    if ( is_wp_error($post) || $post->post_type != 'events' ) {
        return $post_link;
    }
    return str_replace('%event_id%', $post->ID, $post_link);
}

+1 for getting me most of the way

6
  • what did you use as slug for cot?
    – Bainternet
    Commented Mar 2, 2012 at 20:16
  • @Bainternet the slug is auto added to the end by WordPress so there is no need to use %postname% otherwise you get the slug twice in the URL
    – Scott
    Commented Mar 2, 2012 at 20:23
  • nice, so you ended up using news/events/%event_id%/ ?
    – Bainternet
    Commented Mar 2, 2012 at 20:46
  • yup but without the trailing slash
    – Scott
    Commented Mar 3, 2012 at 8:48
  • What i have to do if i want say adding "blog" before the wordpress default post (no matter what is in the permalink structure on settings).
    – Sisir
    Commented Apr 21, 2012 at 10:03
7

Try this First add to %event_id% to your slug:

$args = array(
    'labels' => $labels,
    'public' => true,
    'hierarchical' => false,
    'rewrite' => array(
        'with_front' => false,
        'slug' => 'news/events/%event_id%/%postname%'
    ),
    'supports' => array( 'title', 'editor', 'thumbnail' )
);
register_post_type('events',$args);

then add a filter to the single event premalink:

add_filter('post_type_link', 'custom_event_permalink', 1, 3);
function custom_event_permalink($post_link, $id = 0, $leavename) {
    global $wp_rewrite;
    $post = &get_post($id);
    if ( is_wp_error( $post )  || 'events' != $post->post_type)
        return $post_link;
    $newlink = $wp_rewrite->get_extra_permastruct('events');
    $newlink = str_replace("%event_id%", $post->ID, $newlink);
    $newlink = home_url(user_trailingslashit($newlink));
    return $newlink;
}

that should do the trick but it's untested. And make sure to flush rewrite rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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