For my other blog (Code Quality Code) I’m referring a lot of times a other post as they are all connected to each other. Of course I wanted to automate things and not manually link every time I mention another blog post. To accomplish that I’ve made a small peace of code that will automatically link every reference in the content that is the same as the post title.
Automatically link post titles to their pages
To get started I created a function to get all the post titles. I’ve not done any particular testing for this specific function, but it seemed like a nice optimization to save them as a transient instead of getting them directly from the
_posts table every time. This saves the post titles in the
_options table so there’s only one more simpler query done to retrieve the value.
A couple notes about the used code;
- Only posts will get from this example, you may also want to add pages for example
- Only published posts will be linked, no auto drafts nor draft posts
- It will only link posts with post titles longer than 5 characters (in case you ever write a ultra-simple post title that is too generic it may link wrong content)
- It saves the post titles for a week
Link post titles in the content
Next I created a function that looks for post titles in the post content (case insensitive) and replaces them with a link. The code snippet below shows how its done. I’ve added multiple comments the code to explain what it exactly does.
To optimize things a bit I already pulled the post IDs from in the code above so that won’t need any additional calls to get the post ID later on when searching/replacing.
This should already be enough to get things working on your site.
One important part you don’t want to forget is to clear the cache (transient) when you add/modify a post. The following code snippet re-creates the transient with the latest post titles every time you save a post.
Thats it! It will now automatically link any references in the content you make to post titles. Do keep in mind that these are dynamic links, so whenever you change a post title and not change your content it may no longer link automatically.
The full script is available here; https://gist.github.com/JeroenSormani/181b8c8a1e5ae6ab8d12
I would love to hear from you if this was useful in any way, have feedback, missing something that you’d love to see or just a Thank you 🙂