Development

Auto-create URL Redirects in Feeds

I’m working on a website redesign. The original site used awful URL aliases where nearly everything got a URL like /content/title-of-page-would-end-up-looking-like-this. There are no “sections” to speak of in the URL structure, and there are several thousand nodes! I’m migrating most of the content from the “old” site to the new one using Feeds. Rather than manually mess with rewrite rules, I figured I should just create a redirect at the time of migration. We typically handle redirects/rewrites using the redirect module. So, how do you do this?

The first step is to capture the old URL. In my CSV export View on the old site, I simply included the URL alias (Content: Path in views) with a label of twentyfifteen_url_alias. We’re launching this new site in 2016, so I’m calling anything old-site-related twentyfifteen.

Now we have to make use of this new column in the CSV. It’s easy enough to call in the new source field, but what do we assign it to (what is the target in Feeds-speak)?Screenshot_2016-01-28_07-07-06

This is where we have to do some coding. We need to store our twentyfifteen_url_alias value somewhere, and it’d be best to do so temporarily. There’s no reason to hold onto this value after we create the redirect.

To do this, we need to setup a new target. We use hook_feeds_processor_targets_alter() for this.

Here’s what that looks like in my twentyfifteen_importers custom module:

Notice there is a callback function. We need to create that function:

At this point we should be able to refresh the feeds “Mapping” screen to see the new target. You might be wondering, though, whether or not this will do anything at this point. Screenshot_2016-01-28_07-13-03The answer is no, it won’t do anything more than add the value temporarily to the entity that’s being processed. Of course, we want to make a new URL redirect out of this value. To do this we implement the hook_node_insert() hook (because this hook will execute after the node object gets a proper node ID).

That’s all there is to it! As feeds processes each entity it will look for a twentyfifteen_url_alias property and will create a new redirect (in the Redirect module) if the redirect does not exist yet.

Leave a Reply

Your email address will not be published.