Fredmat
Fredmat

Reputation: 958

WP Rewrite - Add post ID to URL

I have a custom post type (job) in my WordPress theme.

Posts of this type are inserted by users themselves, but if two or more jobs are inserted with the same title, the slug will be:

www.mydomain.com/job/title-choosen-by-user
www.mydomain.com/job/title-choosen-by-user-2
www.mydomain.com/job/title-choosen-by-user-3
...

Is it possible to keep the same slug and add the post ID in the URL using any rewrite? The result would be:

www.mydomain.com/job/100/title-choosen-by-user
www.mydomain.com/job/101/title-choosen-by-user
www.mydomain.com/job/102/title-choosen-by-user
...

Any help would be appreciated. Thank you

Upvotes: 1

Views: 2058

Answers (2)

Dhrumil Kumbhani
Dhrumil Kumbhani

Reputation: 141

Yes, it's possible to add the post id in the URL for that add the below code in your function.php in WordPress.

function custom_job_permalink( $permalink, $post ) {
    if ( 'job' === $post->post_type ) {
        $permalink = trailingslashit( home_url( "/job/{$post->ID}/{$post->post_name}" ) );
    }
    return $permalink;
}
add_filter( 'post_type_link', 'custom_job_permalink', 10, 2 );

function custom_job_rewrite_rules( $rules ) {
    $new_rules = array();
    $new_rules['job/([0-9]+)/(.+)/?$'] = 'index.php?job=$matches[1]';
    return array_merge( $new_rules, $rules );
}
add_filter( 'rewrite_rules_array', 'custom_job_rewrite_rules' );

Hear the First function modify the permalink for the job post type. and the second function is to use the add the custom rewrite rule to the map new URL.

Upvotes: 0

henrywright
henrywright

Reputation: 10240

Perhaps try changing your permalink structure in Settings > Permalinks under the WP admin dashboard.

Try:

/%post_id%/%postname%/

Upvotes: 1

Related Questions