CPT Post Title Permalink: Replace “@” (or all special characters) with dash “-” instead of just removing
-
13-04-2021 - |
Question
I have Custom Post Type "Email", where the Post Title is always going to be an email address, ie: example@domain.com
The problem I am having is the "@" is being removed in the permalink: ../exampledomain-com
I would like it to save as: ../example-domain-com
Replacing the "@" with a "-"
I tried the following from here, but as someone more knowledgeable will quickly see, it doesn't apply to the permalink:
function at_to_dash($title) {
return str_replace('@', '-', $title);
}
add_filter('sanitize_title', 'at_to_dash');
Solution
Just make sure your filter runs before the one that Wordpress itself applies - add a priority of 9:
add_filter( 'sanitize_title', function( $title ) {
if ( FALSE !== strpos( $title, '@' ) ) {
$title = str_replace( '@', '-', $title );
}
return $title;
}, 9 );
Usage:
echo sanitize_title( 'mytitle@example.org' );
Output:
mytitle-example-org
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange