To generate custom permalink based on custom field, try the following steps: -
Step 1: Rewrite the Custom Post Type Slug
Assuming you are a developer on this project, rewrite the slug for custom post type while registering it. Set the slug
to any-keyword-or-cpt-base/%custom-field-name%
See the following example for your case. In this example, I used student-properties
as CPT slug base for permalinks and then a slash /
followed by modifier as %city%
which will be replaced in step 2 with actual value of city for each post permalink.
$rewrite = array(
'slug' => 'student-properties/%city%',
'with_front' => true,
'pages' => true,
'feeds' => false,
);
$args = array(
'label' => __( 'Properties', 'ds' ),
'description' => __( 'Properties', 'ds' ),
// 'labels' => $labels,
// 'supports' => array( 'title', 'editor', 'thumbnail', 'page-attributes' , 'custom-fields'),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-excerpt-view',
'menu_position' => 2,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => $rewrite,
//'capabilities' => $capabilities,
'show_in_rest' => true
);
register_post_type( 'properties', $args );
Step 2: Add filter for post_type_link
To replace the %custom-field-name% that was previously set in rewrite slug of custom post type, we need to filter the output of post permalink in the following way: -
function digitalsetups_single_property_permalink( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
$property_city = get_post_meta($post->ID, 'property_city', true);
if($property_city) {
return str_replace( '%city%' , $property_city , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'digitalsetups_single_property_permalink', 1, 3 );
In the above code, the custom field name or identity is property_city
. We get the property_city value and if its not false (you can add additional validations here), we replaced %city%
with the property_city value.
Notes & Tips:
These steps are for custom field.
In case you want to add taxonomy term value in the rewrite slug, get
the terms for the taxonomy in the filter and replace with term slug.
Additionally, just for taxonomy case & to ensure consistency in
URLs, set the taxonomy rewrite slug to same as CPT base that you
used in CPT rewrite slug. Let me know if this is the case. I'll give
code example and more clarification.
If you are using a plugin to rewrite CPT base you can set base from
there e-g: student-properties/%city%
and then in replace %city%
to your value either from custom taxonomy or custom field or
something else via post_type_link
filter - See step 2.