将JSON-LD(Schema)脚本注入WordPress站点的头部

问题描述 投票:0回答:2

我有一堆JSON-LD文件,我想注入各种页面的头部,有些是有条件的。我正在使用WordPress,他们的建议是使用像wp_enqueue_script这样的函数。困难在于我还没有找到使用<type>函数编辑wp_enqueue_script属性的方法。

我能够像这样笨拙地使用PHP(也许有更好的PHP函数?):

// header.php

<head>
    ...all the regular stuff..

    ..near the bottom..
    <?php
        if ( is_front_page() ) {
            echo file_get_contents(get_template_directory() . '/assets/structured-data/local-business.js');
        } 
    ?>

</head>

我试图注入的脚本格式如下:

// JSON-LD format
<script type="application/ld+json">
{
    "@context": "http://schema.org",
    "@type": "localBusiness",
    "currenciesAccepted": ...
}
</script>

所以我只是试图读取文件。当我尝试包含多个脚本时,这会中断。

我想遵循WP的建议,并使用像wp_enqueue_script()这样的方法,但到目前为止,我还没有找到办法做到这一点。除非我可以将脚本标记为jaz-LD所需的type="application/ld+json",否则整个函数将无法工作。

javascript wordpress schema json-ld structured-data
2个回答
0
投票

我目前这样做的方式是使用add_action();

add_action( 'wp_head', 'my_theme_schema' );

然后在my_theme_schema中,我构建我的模式,然后使用脚本标记输出它。 (我通常用数组构建模式)。

function my_theme_schema() {
  $schema = [];
  ... // build up the schema
  $output = json_encode( $schema, JSON_UNESCAPED_SLASHES );
  ?>
    <script type="application/ld+json">
      <?= $output; ?>
    </script>
  <?php
}

这让我有机会把它放在functions.php中。

另外,我通常不把它放在头部,我把它放在页脚中。

add_action( 'wp_footer', 'my_theme_schema' );

我不知道一个人本来就更好,我只是更喜欢页脚中的JS。


0
投票

我找到了一种方法:

//here we enqueue a dummy script to help us with what we want to achieve
add_action('wp_enqueue_scripts', 'myslug_wp_load_files');
function myslug_wp_load_files()
{
    wp_register_script( 'myslug-dummy-handle-json-footer', plugins_url('scripts/loader.js', __FILE__), [], '', true );
    wp_enqueue_script( 'myslug-dummy-handle-json-footer'  );
}

//here we construct our ldjson and add it to our enqueued script
add_action('wp_head', 'myslug_construct_ldjson');
function myslug_construct_ldjson()
{
    $my_ldjson = '{construct_here_your_ldjson}';
    wp_add_inline_script( 'myslug-dummy-handle-json-footer', $my_ldjson );
}

//here we add a filter to the script loader, and modify text/javascript to application/ld+json
add_filter( 'script_loader_tag', 'myslug_async_tag', 10, 3 );

function myslug_async_tag( $tag, $handle, $src ) 
{
    if ( $handle !== 'myslug-dummy-handle-json-footer' ) 
    {
        return $tag;
    }
    $tag = str_replace("type='text/javascript'", "type='application/ld+json'", $tag);
    return $tag;
}

上面的脚本注册并排队一个虚拟脚本 - 几乎可以是任何东西(甚至是空白)。此外,它将动态生成的JSON-LD添加到虚拟脚本,然后它过滤所有脚本,仅选择我们创建的脚本,并使用类型'application / ld + json'替换类型'text / javascript'。

© www.soinside.com 2019 - 2024. All rights reserved.