I’ve asked few time how to inject specific content on a single post or single page using my Header and Footer plugin. It’s not an immediate implementation since it requires to use some PHP code which could result a bit unreadable over time (by non coders).

In this example we still use a bit of PHP code but in combination with Advanced Custom Fields (ACF) to make the configuration more clear an easy.

The result we want to get with this example is simple: the ability to add a piece of extra CSS in a specific post, be theme change proof and easy to use, with less PHP code as possible.

Tech note: the same result can be obtained using the standard custom fields of WordPress, but they are less easy to use.

Let’s start

We start installing ACF and adding a group of extra fields with a special field we name “css”, a textarea. This field will contain optional CSS rules for each post.

Pay attention to set the field as no formatting (see the picture).

Now while editing a post you have a new configuration textarea where to put your CSS post-specific rules:

To inject those rules in the head of the post page, we can use Header and Footer plugin and the function get_field() of ACF.

We need to use a little bit of PHP, but it is very simple and clear.

This one is the special paragraph and the rules above are applied right now on this post. It has a background color.

If you look at this page in a small device (or shrink the window, the paragraph will change its background color).

Looking at the page source for this post, you can find the injected CSS:

While on other posts you’ll find only an empty style block (it’s ok!).

Extension

This example is rather simple and I’m sure you can find other and more meaningful applications. ACF is very powerful to add custom fields easy to setup and ready to be used by non tech bloggers.

This example shows you how to make that kind of custom implementations theme-indipendent. I’ve see so many time blogs broken after a theme change just because the theme was modified (even a child theme could not save you).

To extend this example, think about custom rules to inject ads. Recently I’ve added a custom checkbox field to mark a post as “sponsored”. Those kind of post must not contain ads.

In the “before the post content” configuration of Header and Footer, where the ad was injected I added:

<?php if (!get_field('sponsored')) { ?>
[ads]
<?php } ?>

Easy and stable overtime.

Yes, all that requires a little bit of coding we could think about a meta language to make that even more easy and clear… maybe in the future!

Similar Posts