1

My current permalink setting is /%postname%/%post_id%/. Would like to use the same with CPT. Currently the URL looks as site.com/questions/title/

Would like to get post id at the end of the url on every single cpt post, similar to that of post type post...

The closest function i found is... (which outputs site.com/questions/postid/)

add_filter('post_type_link', 'change_post_type_link', 1, 3);

function change_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'questions' ){
        return home_url( 'questions/' . $post->ID );
    } else {
        return $link;
    }
}

add_action( 'init', 'change_rewrites_init' );

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

TIA

1

Try this :

function change_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'questions' ){
        return home_url( 'questions/'. $post->post_name .'/'. $post->ID );
    } else {
        return $link;
    }
}

add_action( 'init', 'change_rewrites_init' );

function change_rewrites_init(){
    add_rewrite_rule(
        'questions/([a-z-]+)/([0-9]+)?$',
        'index.php?post_type=questions&p=$matches[1]&postid=$matches[2]',
        'top' );
}

Here post slug is attached after questions in the URL. For example questions/q-slug/45. Rewrite rule is changed accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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