<?php
/*
WARNING :
  https://woocommerce.com/
    needed
*/

if( !function_exists('the_product_json_ld') ){
  function the_product_json_ld($post_id, $product_id){
    if(!$post_id) {
      global $post;
      $post_id = $post->ID;
    }
    if(class_exists('woocommerce')) { // woocommerce
      $prod = wc_get_product( $product_id );

      $json_ld = array(
        "@context" => "http://schema.org",
        "@type" => "Product",
        "name" => get_the_title($post_id),
        "description" => get_the_excerpt($post_id),
        "image" => array(
          "@type" => "ImageObject",
          "url" => get_the_post_thumbnail_url($post_id, 'medium'),
          "height" => "300px",
          "width" => "300px",
        ),
        "offers" => array(
          "@type" => "Offer",
          "priceCurrency" => "EUR",
          "price" => $prod->get_price(),
          "availabilty" => $prod->is_in_stock()
        ),
      );
    } else { // not woocommerce
      $json_ld = array(
      "@context" => "http://schema.org",
      "@type" => "Product",
      "name" => get_the_title($post_id),
      "description" => get_the_excerpt($post_id),
      "image" => array(
        "@type" => "ImageObject",
        "url" => get_the_post_thumbnail_url($post_id, 'medium'),
        "height" => "300px",
        "width" => "300px",
      ),
      "offers" => array(
        "@type" => "Offer",
        "priceCurrency" => "EUR",
        "price" => get_field('price')
      ),
    );
    }
    $json = json_encode($json_ld);
    $output = '<script type="application/ld+json">'.$json.'</script>';
    print($output);
  }
}
