Open jdevalk opened 2 months ago
Howdy!
I don't think setting an ID to the script is helpful other than for targeting TSF's performance specifically. So, it's a "maybe later" for me.
How do Schema.org's Validator, Google, Pinterest, etc. pull the scripts? I think it's better to mimic their behavior. A script like this ought to do the trick, and it'll also grab anything from other plugins, like WooCommerce, as well:
function getJsonFromPage() {
const data = {};
document.querySelectorAll( 'script[type="application/ld+json"]' ).forEach(
script => {
try {
const json = JSON.parse( script.innerText );
if ( json ) {
// Assign to 'WebSite' it hasn't a type or ID.
const key = json['@id'] || json['@type'] || 'WebSite';
data[ key ] ||= [];
data[ key ].push( json );
}
} catch ( e ) {
console.error( 'JSON-LD parsing error:', e );
}
}
);
return data;
}
Call getJsonFromPage()
to get all the data sorted by type. I chose to put everything under 'WebSite' for when an identifier or type is missing, but your use case might require an alteration herein.
But if you genuinely require to query the script specifically, you can use this filter to add an id
-attribute like tsf-website-schema
to the script element already:
add_filter(
'the_seo_framework_meta_render_data',
function ( $data ) {
if ( isset( $data['schema:graph'] ) ) {
$data['schema:graph']['attributes']['id'] = 'tsf-website-schema';
}
return $data;
},
);
Setting attributes like this is new with TSF v5.0+. It won't work for Extension Manager's scripts (like Article and LocalBusiness), as that is still in a transitionary phase between TSF v4.x and v5.x. But in a future update, I'll merge them with TSF's Schema.org graph output.
Let me know if this is helpful. Have a lovely day 😄
I currently have a site that is using the SEO Framework and I need access to its JSON output so I can use the data in there in Google Tag Manager to enrich the data we're measuring. Unfortunately, those JSON blocks have no
class
orid
attributes, they're just plain, for example, from your own front page:Could you give those
script
tags an identifiable class liketsf-website-schema
andtsf-localbusiness-schema
or something similar? That way I could grab them with JavaScript a lot more easily.