0

I have a custom post type called "equipment". I would like the permalink structure to be:

example.com/equipment/%post_id%-slug

I specifically want it to use a dash and not a slash (i.e. - "id-slug" not "id/slug"). Every possible solution I've found from googling has used slashes and I just can't get it to work with a dash.

I also want to prevent WordPress from adding on the additional number if there's two posts with the same title. Example:

example.com/equipment/45-awesomeness
and
example.com/equipment/46-awesomeness-2

I think the solution is to use add_rewrite_rule, but I'm a bit confused with the regex stuff.

The following code did work to replace the post name with the id in the slug:

function equipment_links($post_link, $post = 0) {
    if($post->post_type === 'equipment') {
        return home_url('equipment/' . $post->ID . '');
    }
    else{
        return $post_link;
    }
}
add_filter('post_type_link', 'equipment_links', 1, 3);


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

It did return a url of "example.com/equipment/123", but I would like to tack on "-post_name" to the end of that "123".

0

I don't have much experience with coding rewrites, but could you just add $post->post_name into your return statement?

return home_url('equipment/' . $post->ID . '-' . $post->post_name );

There are a few other ways to change the permalinks that I have used that may also help you:

  1. The easiest way to change your permalink structure is probably to use a custom structure by going to the admin menu, settings > permalinks. Select custom structure and set it to /%post_id%-%postname%/
  2. If you are looking to edit the permalink structure for the specific post type without touching any code or another post type, I would suggest downloading a plugin like "Custom Post Type Permalinks" or "Simple Post Type Permalinks" both by Toro_Unit.

In regards to the unique identifier, you want to remove at the end.. I don't have that answer. However, if you are willing to use a .htacess rewrite instead of php, you may want to give this a try:

https://stackoverflow.com/questions/14635438/remove-trailing-number-from-url-via-htaccess

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.