如何在 JSON-LD 中包含 WordPress PHP 标签?

How do I include WordPress PHP tags in JSON-LD?

我想将 JSON-LD 结构化数据添加到我的 WordPress WooCommerce 网站,以增加我在搜索引擎结果页面上出现丰富网页摘要的机会。

我想首先将它添加到我的产品页面。

如果我在 header-shop.php...

中包含以下代码
    <!-- Include Schema Markup File
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<?php include('json-ld.php'); ?><script type="application/ld+json"><?php echo json_encode($payload); ?></script>

如何在 json-ld.php 文件中引用 PHP 标签,例如 <php the_title(); ?>

是不是像下面这么简单?

<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "<?php the_title(); ?>",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>

您可以在 PHP 中执行此操作以打印到您的页面。通过完整地回显您的脚本,您可以连接内联函数。

echo '
<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "'. the_title() .'",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>
';

对于文章,这是我使用的(我猜它不会很复杂地适应产品):

    function add_ld_json()
    {
        // get post thumbnail
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'post-full');
    
        // get canonical
        $post_full_url = wp_get_canonical_url();
    
        // get title
        $page_h1 = the_title('', '', false);
    
        // create ld-json with structured data
        $ld_json = <<< EOT
    
        <script type="application/ld+json">
        {
            "@context": "https://schema.org/",
            "@type": "TechArticle",
            "mainEntityOfPage": {
                "@type": "WebPage",
                "@id": "{$post_full_url}"
            },
            "headline": "{$page_h1}",
            "image": "{$thumb[0]}",
            "author": {
                "@type": "Organization",
                "name": "your-organization-name"
            }
        }
        </script>
    EOT;
    
        echo "{$ld_json}";
    }

然后,您必须将其包含在您的 header.php 或您的页面代码所在的任何位置。我还排除了 404 页面和首页(对于这些页面没有多大意义):

if (!is_front_page() and !is_404())
add_action('wp_head', 'add_ld_json', -1);

建议在所有其他元标记(如 title/description 等)之前在头部包含 ld-json。