Sandeep Kumar Mishra
Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.
Let’s dive into the pre_wp_unique_post_slug filter hook in WordPress. This hook is a lifesaver when you want to short-circuit the unique slug generation and return the value you prefer. You just need to register it using add_filter in your theme’s functions.php file or a custom WordPress plugin. It’s always wise to go the plugin route to avoid issues during theme updates.
Here’s how to get started:
Below are the 6 parameters required to use this hook:
apply_filters( 'pre_wp_unique_post_slug', string|null $override_slug, string $slug, int $post_ID, string $post_status, string $post_type, int $post_parent )
Below are three examples of how you can use this hook:
In this example, we’ll define a function weplugins_modify_pre_wp_unique_post_slug_defaults that takes the 6 parameters and registers the filter.
function weplugins_modify_pre_wp_unique_post_slug_defaults($override_slug, $slug, $post_ID, $post_status, $post_type, $post_parent) {
// Update the $override_slug variable according to your website requirements and return this variable.
return $override_slug;
}
// add the filter
add_filter( "pre_wp_unique_post_slug", "weplugins_modify_pre_wp_unique_post_slug_defaults", 10, 6 );
This example conditionally modifies the slug based on post type.
function weplugins_modify_pre_wp_unique_post_slug_conditional($override_slug, $slug, $post_ID, $post_status, $post_type, $post_parent) {
if ($post_type == 'custom_post') {
$override_slug = 'custom-' . $slug;
}
return $override_slug;
}
// add the filter
add_filter( "pre_wp_unique_post_slug", "weplugins_modify_pre_wp_unique_post_slug_conditional", 10, 6 );
To remove a hook callback, use the example below. Make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.
remove_filter( "pre_wp_unique_post_slug", "weplugins_modify_pre_wp_unique_post_slug_defaults", 10, 6 );
If you’re having any trouble using this hook or need customization, please contact our team, and we’d be happy to assist you.
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.