permalinks – Set new url from custom post field

Question

I’ve create a new custom post type “Event”. I’ve added a custom field (Post Object) to the post type “Post” were you can select the corresponding Event.

So I create post new post and then I select Event X.

I want my URL to be domain.com/news/event-x/post-name.

I’ve create a function:

function custom_url_posts_event ($urlsub, $post) {
    if ($post->post_type == 'post') {
            
        //get event id
        $eventId = get_post_meta($post->ID, 'event_obj', true);
       
        //get venue slug
        $eventSlug = get_post_field( 'post_name', $eventId );
        
        $eventSlugSlash="https://wordpress.stackexchange.com/".$eventSlug;
        
        if (!empty($eventSlug)) {
            $point = strrchr(rtrim($urlsub, "/"), "https://wordpress.stackexchange.com/");
            $urlsub = str_replace($point, "/$eventSlug$point", $urlsub);
        }
    }
    return $urlsub;
}

add_filter('post_type_link', 'custom_url_posts_event', 11, 4);

When I output $urlsub I get the correct URL: domain.com/news/event-x/post-name
So I guess that the filter above works correctly.

But the actual URL is still domain.com/news/post-name
The URL isn’t updated with the Event slug (event-x in this case).

I’ve also tried to change the permalink structure under Settings with:
Custom struction: domain.com/news/%event_obj%/%postname%/

But %event_obj% is literally printed in the URL.

0
Dennis 2 months 2022-12-09T04:53:48-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse