Custom post type permalink: only use %post_id% and remove %postname%

I found the answer myself – so here is the update to above problem:

Custom post type registration:

function create_post_type_mycustomname() {
    $args = array(
        'capability_type' => 'post',
        'has_archive' => 'mycustomname',
        'rewrite' => array(
            'slug' => '/mycustomname',
            'feeds' => false
        )
    );

    register_post_type('ctp_mycustomname', $args);
}
add_action('init', 'create_post_type_mycustomname');

Change the links:

function mycustomname_links($post_link, $post = 0) {
    if($post->post_type === 'ctp_mycustomname') {
        return home_url('mycustomname/' . $post->ID . "https://wordpress.stackexchange.com/");
    }
    else{
        return $post_link;
    }
}
add_filter('post_type_link', 'mycustomname_links', 1, 3);

Add the correct rewrites rules:

function mycustomname_rewrites_init(){
    add_rewrite_rule('mycustomname/([0-9]+)?$', 'index.php?post_type=ctp_mycustomname&p=$matches[1]', 'top');
}
add_action('init', 'mycustomname_rewrites_init');

Flush rewrite-rules in WordPress backend afterwards and you are good to go!

Leave a Comment