1

I am trying to re-write my WooCommerce product urls to be have the Post ID at the end, like this:

/product/product-name-post-id/

I've used the code from this thread How to rewrite URI of custom post type? which is working, but we have /product/post-id-product-name/.

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

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

add_action( 'init', 'wpse33551_rewrites_init' );

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

I can't work out how to work the re-write rule in the second function here to get the Post-ID to be at the end?

3
  • Have you flushed your permalinks after setting this ? The code looks good for the permalink part. To flush permalinks, go to Settings > Permalinks and just hit the "save" button.
    – Gregory
    Jun 7, 2019 at 13:40
  • Yes! The code works ... BUT ... it's backwards, and I believe it is this part that in the add_rewrite_rule is the culprit: 'product/([0-9]+)?$', It's giving the format /product/id-postname/ but I would like it to go /product/postname-id/.
    – SeanAUS120
    Jun 7, 2019 at 13:45
  • i don't understand what you want. URL is ok, but you have 404 on front ? have a look to this plugin that can help you understand what does do your rewrite rules wordpress.org/plugins/rewrite-rules-inspector
    – Gregory
    Jun 7, 2019 at 13:51

1 Answer 1

0

This should work:

add_action( 'init', 'wpse33551_rewrites_init' );

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

The filter function is changing the permalink to like product/my-product-name-88. You just need to tweak the regex in the second function to deal with that pattern.

The regex is:

product/ – matches the literal string product/

.+ – matches one or more other characters

\- – matches a hyphen (the backslash escapes it, so the regex engine doesn't think it's a special regex operator, like in the next bit)

([0-9]+)?$ – matches and captures one or more numbers at the end of the URL

As @gregory says, after making this change you need to click the save button on your permalink page wp-admin/options-permalink.php to flush the rewrite cache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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