Site icon Hip-Hop Website Design and Development

Dynamic CPT permalink structure based on ACF field value

There are already few questions on this topic but they are not helping my problem. So what I want to achieve is dynamic CPT permalink structure based on the ACF (radio) value.

// _cb stands for checkbox
radio_acf_cb = foo
radio_acf_cb = bar

Depending on what’s the user’s choice the permalink would look like this

// fixed_word is the first part of the permalink which will be static
// foo/bar are the values based on the choice from the ACF
// 123 is the post ID 

example.com/fixed_word/foo/123 // if foo is chosen
example.com/fixed_word/bar/123 // if bar is chosen

Here’s what I tried so far:

add_filter( 'post_type_link', 'so51217355_post_type_link', 10, 2 );

function so51217355_post_type_link( $permalink, $post ) {

    if ( 'my_cpt' === $post->post_type ) {

        $choice = get_field('foo_bar', $post->ID) // foo or bar

        $choice_slug = $choice == 'foo' ? $choce : 'bar';


        if ( $choice_slug ) {
            // This would give me example.com/fixed_word/foo/123
            // or example.com/fixed_word/bar/123
            $permalink = '/fixed_word/' . $choice_slug . $post->ID;
        }

    }

    return $permalink;
}

Now I know that I need to write some custom rewrite rule with add_rewrite_rule() but I am not sure how to set the conditions.