Recovering lost custom CSS in WordPress

This is a note to self in case this happens again…

Today we discovered that the custom CSS on a WordPress site had disappeared. The whole section was empty and the site looked a bit shonky around the edges.

I had backups, but didn’t want to go restoring before first seeing if there was a “lighter touch” way to restore the custom CSS.

I had no idea where the custom CSS was stored in the database, so I took a hammer to crack the nut. Did a mysqldump and opened it in an editor. Quickly found that it wasn’t stored in wp_options, instead it was in wp_posts.

The custom css is stored like a normal post and so has a bunch of revision history records. This query showed me what was stored and from what date:

select post_status,post_modified from wp_posts where post_content like '%custom_css%';

I then pulled back the most recent CSS:

select post_content from wp_posts where id = XXX;

The settings are stored in a JSON string:

{
    "custom_css[astra-child]": {
        "value": "... CUSTOM CSS HERE ..." 
}

I couldn’t quite cut and paste the CSS since it had “\n” newlines in it. So I simply cut and pasted the string into a quick two line python script:

css = "pasted custom CSS"
print(css)

Which gave me what I needed. I’m sure that there’s an easier way, but it did the trick. Pasted the CSS back into the settings and we were good to go.