How can i add a JSON script (Schema data) to the head of each post's page once the post is saved on wordpress

Viewed 11

I wrote a php snippet that accesses data in the database each time a post is saved or created and stores it in a string variable using the hook add_action("wp_insert_post",...) to produce a script in google rich format. I'm however facing difficutlties in adding the script corresponding to each post in their respective web pages. For length reasons i have added a shorter version of my code.

add_action( 'wp_insert_post','post_update', 10,3);

function post_update( $post_id, $post, $update ){

$post = get_post($post_id);
   
$output.='
<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "Event",'; 


$postMeta= get_post_meta(get_the_ID());

$StartTime = $postMeta['event_start_time'][0];
$EndTime = $postMeta['event_end_time'][0];
$StartDate= $postMeta['event_start_date'][0];
$EndDate = $postMeta['event_end_date'][0];

if (!empty($StartTime) && !empty($EndTime)){
    $StartDate=$StartDate."T".$StartTime.":00";
    $EndDate=$EndDate."T".$EndTime.":00";
}

$EventName= !empty( $post->post_title ) ? $post->post_title : '';

$output.= '
    "name": "'.$EventName.'",
    "image": "......"
    "startDate": "'.$StartDate.'",
    "endDate": "'.$EndDate.'",
 }
</script>';
 }

How can i add the variable output to the pages belonging to the corresponding post (which are events in this case)

0 Answers
Related