1

I have a series of URLs where the permalink ends with a hyphen. They come from a previous CMS where this apparently wasn't an issue, but in WordPress they result in a 404.

I'm noticing that when I edit the permalink in the CMS and remove the hyphen, the URL starts working with and without the hyphen at the end, which is fine.

But since there are 600+ of these URLs, what is the best way to do a bulk fix for this case?

1

You could code a database patch in PHP/with the WordPress APIs, but since it sounds like you won't be repeating this process frequently, I think that's probably overkill. The most straightforward approach to bulk changes like this is a quick SQL update directly on the database.


Bulk Update via SQL Query

One large exception to performing a bulk update with a direct SQL query is the case where the fields you intend to modify contain serialized data, in which case using PHP/the WordPress APIs or a specialized tool might prove more convenient.

Luckily, post slugs are stored as plain strings in the post_name field, so a query to remove trailing hyphens is fairly intuitive:

UPDATE wp_posts SET post_name = TRIM(TRAILING "-" FROM post_name) WHERE post_name LIKE "%-"

Since direct SQL queries circumvent all manner of checks and balances, it is prudent to back up your database before executing any database-altering query.


Link Redirection via Server Configuration

Since it sounds like this content has been around for while and you might have users attempting to access it using old, hyphen-terminated URLs, you may want to add a rewrite rule to your .htaccess file (or equivalent) in order to redirect old URLs to their new hyphen-less counterparts:

# BEGIN WordPress
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)-$ $1 [QSA,R=301,L]  # Redirect requests to hyphen-terminated URLs
  RewriteRule . /index.php [L]
</IfModule>
# END WordPress

This may need to be modified to fit your installation's configuration. Note that it will interfere with any other functionality that depends on non-filesystem, hyphen-terminated URLs, if it exists.

  • But why the WP UI doesn't allow the trailing dash -? Is there any reason for that? – Scott Sep 9 '18 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.