1

I am trying to build a custom permalink in wordpress for my custom post type artikelen (exact slug). I found code online and it seems to do the work with transforming the links with a custom structure %postname%/%postid%, but when I save my permalinks and go to a detail page I get a 404 error.

I am posting my code to demonstrate my way of working.

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

function wpse33551_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'artikelen' ){
        return home_url( $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=artikelen&p=$matches[1]',
        'top' );
}
1
product/([0-9]+)?$

translates to product/ followed by any number or nothing (and nothing more, not even a trailing slash). This doesn't sound like the thing you want to achieve.

Instead, try the following

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

which translates to:

  • ^ start of the string (ie, there is nothing else in front)
  • ([^/]+): at least one character that is not /
  • /: a slash
  • ([0-9]+): at least one number
  • /?: zero or one (trailing) slash
  • $: end of the string

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.