1

I have been pulling my hair out trying to figure out how to get this to work. The site I am working on has two post types created using the Toolset plugin. One for Regions and one for Locations. Both are hierarchical and both have a lot of posts created already.

The client now wants the Locations to be children of Regions. Advanced Custom Fields was already being used to form a relationship between each Location and the Region they are in so I thought this might work. Here's what I am trying to accomplish. If we currently have a region: example.com/regions/california/los-angeles. And a location in that region is now: example.com/locations/downtown-store. The desired result is example.com/locations/california/downtown-store.

I've tried a bunch of different approaches but nothing has worked. All the rules that show the proper permalink in the admin products a 404 error. Here's my latest attempt:

function region_permalinks( $post_link, $post ){
     if ( is_object( $post ) && $post->post_type == 'location' ){
        $regions = get_field('region');
                foreach( $regions as $region ):
                    $regionurl = get_permalink( $region->ID );
                        $baseurl = "http://www.example.com/regions/";
                        $regionslug = str_replace($baseurl, "", $regionurl);
            endforeach;
        if( $regions ){
            return str_replace( 'locations/' , $regionslug , $post_link );    
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'region_permalinks', 1, 2 );
  • Your code just alters the links when you output a URL, to make those URLs resolve correctly, you need to add rewrite rules. – Milo Apr 2 '18 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.