Format Date in ld+json in Custom Code Block for CMS Items

I have blog posts that have ld+json schema markup added to the Custom Code field (“Before body tag”). This works, except the date fields have incorrect format. There are two that need the date format adjusted to be valid:

CleanShot 2023-07-09 at 11.30.50

The current output looks like:

"datePublished": "Jul 07, 2023",
"dateModified": "Jul 09, 2023"

but those should ideally be:

"datePublished": "2023-07-07",
"dateModified": "2023-07-09"

I’ve seen posts around the forum that sort of address how to fix this (using {{wf …}} tags, or manipulating the dates with JS) but I can’t put things together to make this work. I can write some vanilla JS to modify the date, but can’t figure out how to inject that JS variable in the json.

Would be great to have to ability to choose output format on date fields wherever they’re used! Short of that, does anyone have advice on how to solve?

One of the posts where it looks like this was “solved” with {{wf}} shortcode was Alter Date Field Format in Custom Code Embed - #4 by gfirem. If I grab the shortcode for the dates and plug it back into the Custom Code field, it’s highlighted red, like an error, and doesn’t output anything.

CleanShot 2023-07-09 at 12.10.44

Hi!

I had the same problem. I don’t know if this is relevant to you anymore, but for all the others looking for answers, this worked for me:

I found a suggestion from Stackoverflow to “build the schema first then inject it in”.

I used it for my site and tested it with the Rich Result Test and, at the time of writing this, it works. I modified the code a bit though from the Stackoverflow answer.

Modify the schema to your liking, add the code inside the page’s <head> tag and replace (in this example, all the strings starting with “add-”) with your content.

<script>
const published = new Date(Date.parse("add-published-date"))
const updated = new Date(Date.parse("add-updated-date"))
const schema = {
  "@context": "https://schema.org/",
  "@graph": {
    "@type": "BlogPosting",
    "headline": "add-headline",
    "description": "add-description",
    "author": {
      "@type": "Organization",
      "name": "add-name",
    },
    "publisher": {
      "@type": "Organization",
      "name": "add-name",
      "logo": {
        "@type": "ImageObject",
        "url": "add-url",
      },
    },
    "datePublished": published,
    "dateModified": updated,
  },
};

const script = document.createElement("script");
script.type = "application/ld+json";
script.text = JSON.stringify(schema);

document.getElementsByTagName('head')[0].appendChild(script);
</script>

Try this;