Category Archives: Programming

WordPress Logo

Prepend a Taxonomy to the WordPress Permalink Structure

I was tasked with creating a WordPress site that displays blog posts for different suburbs. Each of these suburbs is required to have its own homepage, with only relevant posts for the suburb listed.

Isn’t that what WordPress Multisite is for?

Each site in a WordPress Multisite network is managed individually. To send a post to another site in the network, you need to use a plugin like Broadcast. For a small number of sites, this is ok. But what if you have hundreds of sites? The answer is obvious. If we use WordPress Multisite, this is going to become really hard to maintain in the long run.

How does it work?

The WordPress permalink structure and rewrite rules will need to be customised in order to make this work. We want to be able to assign posts to taxonomy terms, and have the post list change based on that value.

A default permalink structure might look like this:

What we need to achieve is:

The value of %suburb_slug% will be used to limit the posts displayed using the WordPress query.

yoursite.com – displays all posts.
yoursite.com/suburb – displays posts for the suburb.

Just show me the code.

The sample code below can be added to your themes functions.php file. Please be aware that it will not cover all edge cases that you may run into when creating this type of WordPress website.

Remember, whenever you make a change to the permalink structure, you need to save the Permalinks Settings page to flush the rewrite rules.

https://gist.github.com/ThatStevensGuy/39e92db4d38c8b763f55856f38e9f3e0

Performance Issues

The results of all suburb taxonomy terms are stored in a WordPress option. WordPress options are cached for fast retrieval. If you combine W3 Total Cache with dynamic content caching, such as Cloudflare APO, you should have no performance issues.

Custom Post Types

The current version of WordPress (5.7.2) does not apply a filter to replace permalink structure tags with regex for custom post types. I have provided a filter in the sample code that corrects this issue.

WordPress Logo

WordPress Multisite unfiltered_html Capability

User roles other than Super Admin cannot be assigned the unfiltered_html capability in WordPress Multisite. You can set it, but then WordPress disables the capability after the fact.

This creates a unique WordPress challenge. Your site admins will not have the ability to add a hard coded iframe or embed to a post.

Solution

WordPress does not offer an easy function to find a users role. I have provided a function to achieve that as part of the solution.

WordPress Logo

Automatic Featured Image for WordPress Posts

The following script will automatically set the first image in a WordPress post as the Featured Image when the post is saved. You can override the functionality by selecting a Featured Image.

https://gist.github.com/ThatStevensGuy/7020010fe667106f79d2556f386933d0