0

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_rewrite_rule('^food/([^/]*)/?','?item=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);

2
  • 1
    You need corresponding rewrite rules to set the proper query vars for those requests.
    – Milo
    Commented Jan 20, 2015 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
    Commented Jan 20, 2015 at 22:13

1 Answer 1

1

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:

add_rewrite_rule('food/([^/]+)/?$','index.php?post_type=item&p=$matches[1]','top');
6
  • Thanks but still 404. Maybe I should do flush_rewrite somewhere or something similar. @Milo
    – Valeka
    Commented Jan 21, 2015 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
    Commented Jan 21, 2015 at 14:40
  • Thanks, I tried but nothing. I'm going to look for different solution.
    – Valeka
    Commented Jan 21, 2015 at 19:49
  • sorry, there was a typo in the rule, edited version above is tested and working.
    – Milo
    Commented Jan 21, 2015 at 20:04
  • 1
    you would swap post_type=item&p=$matches[1] with item=$matches[1]
    – Milo
    Commented Jan 22, 2015 at 16:30

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.