Manually Define Permalink Sub-Directory For Custom Post Type
Manually Define Permalink Sub-Directory For Custom Post Type
Have you ever wanted to manually define a sub-directory permalink structure for a specific post? Or have a sub-directory permalink automatically added based on a custom taxonomy term the post is assigned to?
Either way, it is possible! Let’s jump into some custom functions.
Before we go further, the first step is to register our custom post type where we want to utilize the permalink structure on. We’ll register this post type called ‘venue’ using the following:
function register_venue() { $args = array( 'label' => 'Venue', 'public' => true, 'show_ui' => true, 'has_archive' => true, 'capability_type' => 'page', 'hierarchical' => false, 'rewrite' => array( 'slug' => 'venue/%location%', 'with_front' => false ), 'query_var' => true, 'menu_icon' => 'dashicons-location-alt', 'supports' => array( 'title', 'editor', 'custom-fields', 'revisions', 'author', 'page-attributes',) ); register_post_type( 'venue', $args ); } add_action( 'init', 'register_venue' );
The important line to take note of is the slug which utilizes the variable %location%. This will be replaced when we create a new post.
Now that we have the custom post type registered, we have two approaches we can use to replace %location% for the individual post. Our first option is going to take a taxonomy term assigned to the post and apply the slug to the permalink.
Here’s what our function would look like. Looking for assigned terms within a custom taxonomy called ‘location’.
function events_permalink_structure($post_link, $post, $leavename, $sample) { if ( false !== strpos( $post_link, '%location%' ) ) { $event_type_term = get_the_terms( $post->ID, 'location' ); $post_link = str_replace( '%location%', array_pop( $event_type_term )->slug, $post_link ); } return $post_link; }
Option #2 could leverage a custom field (in this case using Advanced Custom Fields) to manually assign the permalink directory from a custom field. Here we are grabbing the custom field value ‘location_permalink’ and inserting it into the permalink.
function events_permalink_structure($post_link, $post, $leavename, $sample) { if ( false !== strpos( $post_link, '%location%' ) ) { $event_type_term = get_field('location_permalink', $post->ID); $post_link = str_replace( '%location%', $event_type_term, $post_link ); } return $post_link; }
Enjoy :).
Share Your Thoughts