I have this function and it does just what I need, it replace words in URL perfectly, but links don't work. All links are good and display on site well structured, as I wanted, but just don't open posts. Is there any way that I can make it work?

add_filter('post_type_link', 'replace_link', 1, 3);
function replace_link( $link, $post = 0 ){
    if ( $post->post_type == 'item' ){
        return home_url('food/'. $post->ID);
    } else {
        return $link;
function custom_rewrite_rule() {
add_action('init', 'custom_rewrite_rule', 10, 0);

  • 1
    You need corresponding rewrite rules to set the proper query vars for those requests. – Milo Jan 20 '15 at 22:08
  • Can you please help me there? I tried but it seams like I cant get right URL structure. I edited my function. @Milo – Valeka Jan 20 '15 at 22:13

Your post_type_link uses the post's ID, but the item query var expects a postname. To query by ID you need to use the p query var and set post_type:

|improve this answer|||||
  • Thanks but still 404. Maybe I should do flush_rewrite somewhere or something similar. @Milo – Valeka Jan 21 '15 at 10:11
  • After adding or changing rewrites you must flush rules. Visiting the permalinks settings admin page is the simplest way to do this. – Milo Jan 21 '15 at 14:40
  • Thanks, I tried but nothing. I'm going to look for different solution. – Valeka Jan 21 '15 at 19:49
  • sorry, there was a typo in the rule, edited version above is tested and working. – Milo Jan 21 '15 at 20:04
  • 1
    you would swap post_type=item&p=$matches[1] with item=$matches[1] – Milo Jan 22 '15 at 16:30

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.