Custom post types – Use post_id in permalink structure

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}/.

Read More

How do I do this?

Related posts

Leave a Reply

2 comments

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

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