This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
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:
Parameters
- $override_slug : (string|null) Short-circuit return value.
- $slug : (string) The desired slug (post_name).
- $post_ID : (int) Post ID.
- $post_status : (string) The post status.
- $post_type : (string) Post type.
- $post_parent : (int) Post parent ID.
Below are the 6 parameters required to use this hook:
Live Example
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:
Example 1: Basic Usage
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 );
Example 2: Conditional Slug Modification
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 );
Example 3: Removing the Filter
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 );
Contact Us
If you’re having any trouble using this hook or need customization, please contact our team, and we’d be happy to assist you.
Explore the latest in WordPress
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.