WP add_rewrite_rule with custom field and post name

Viewed 101

I have been trying to get a WP url rewrite to work for the past few hours, but I can't seem to find what's wrong with it.

I have the below code which changes the post URLs to include a custom field value ('custom_id') and the post slug/name. The title change is working fine.

add_filter('post_type_link', 'change_post_type_link', 1, 3);
function change_post_type_link( $link, $post = 0 ){
    if ($post->post_type == 'estate'){
        return home_url('pand/'.get_field('custom_id',$post->ID).'/'.$post->post_name);
    } else {
        return $link;
    }
}

Next, a custom WP rewrite rule is added that checks for the right post to be returned, but I always get a 404 page not found.

add_action( 'init', 'change_rewrites_init' );
function change_rewrites_init(){
    add_rewrite_rule(
        'pand/([0-9]+)/([a-z-]+)?$',
        'index.php?post_type=estate&name=$matches[2]',
        'top' );
}

Anyone have any clues why this isn't working? Thanks!

0 Answers
Related