Hiding container elements based on the state of the Modified Date block in WordPress using CSS

On my single post template I like to show the date the post was most recently modified to make it clear that it had been edited since it was first published. I also do this on my portfolio entries – which you can see on my Where I series of photographs on the bottom left-hand corner.

WordPress’ Modified Date block has a toggle for displaying the date only when the post has been modified, and completely omitting it when the post has not been modified. I like this feature because it keeps my pages nice and clean by only showing the information if needed.

An issue I’ve had on my site for the last several months has been that the Modified Date block doesn’t allow you to have a label next to the date to specify what the date means. Example: “Last updated: Date”. I wanted readers to know what the date meant.

So, in the Full Site Editor in WordPress I added a paragraph block above the date and simply wrote “Last updated:” in it. That works, but the words “Last Updated:” would appear whether or not the Modified Date block was displaying on the page or not. So I ended up with this little orphaned paragraph that meant nothing.

I hadn’t had a meaningful enough time to spend on a solution. I wanted to see if I could create a Block Variation that would allow me to add a label. Or, perhaps even submit a patch to Core to be included in a future WordPress update. And I may still do that.

But for now, I have a solution using CSS’ excellent :not and :has selectors.

First, I used the Group block to group the Paragraph and Modified Date blocks together. Then, I added a specific class to the Group block (this may not be needed, but I wanted it to be specific to me). Then I added the following CSS to my Child Theme’s stylesheet.

.container:not(.container:has(time)) {
  display: none;
}

The Modified Date block adds a time HTML element to the page. If that element does not exist, I do not display the container, which includes my paragraph and label.

If you page through a few of my blog posts you’ll see that the Modified Date block is shown on some of them and not on others.

Last updated:

Powered by Hubbub Pro+