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

How do I do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x