Put post ID on the custom post type URL

It’s quite easy, actually:

  1. Change the generated permalink structure so that it ends with the post ID and not the post slug (but it still contains the post slug):

    // After you registered the post type:
    register_post_type( 'ex_article', $args );
    
    // .. run this code:
    global $wp_rewrite;
    $wp_rewrite->extra_permastructs['ex_article']['struct'] = 'sa/%ex_article%/%post_id%';
    
  2. Then replace the post ID placeholder (%post_id%) in the generated permalink URL with the correct post ID:

    add_filter( 'post_type_link', function ( $post_link, $post ) {
        if ( $post && 'ex_article' === $post->post_type ) {
            return str_replace( '%post_id%', $post->ID, $post_link );
        }
        return $post_link;
    }, 10, 2 );
    

And don’t forget to flush/regenerate the rewrite rules! Just visit the permalink settings page without having to click on the “save” button.

Leave a Comment