You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加按页面ID判断的if条件后,自定义Schema代码失效求助

自定义文章类型单页添加Schema代码时,按页面ID判断的if条件失效问题

我尝试直接添加一段Schema代码(因Yoast SEO无法实现该需求),仅使用JSON数组时代码可正常添加,但添加按页面ID(1385)判断的if条件后代码失效。该页面为自定义文章类型(Custom Post Type)的单页,请问问题出在哪里?

相关PHP代码:

global $post;
if( $post->ID == 1385 ){ 

    $arrJson = array(
        '@context' => 'https://schema.org/',
        '@type' => 'AggregateRating',
        "ratingValue" => "4.93",
        "bestRating" => "5",
        "ratingCount" => "18",
        "itemReviewed" => array(
            '@type' => 'Hospital',
            'name' => 'Practice Plus Group Hospital Barlborough',
            'telephone' => '0330 053 6443',
            "address" => array (
                "@type" => "PostalAddress",
                "streetAddress" => "2 Lindrick Way",
                "addressLocality" => "Barlborough",
                "addressRegion" => "Chesterfield",
                "postalCode" => "S43 4XE",
                "addressCountry" => "UK"
            ),
        ),
    );

    echo '<script type="application/ld+json">';
    echo json_encode($arrJson);
    echo '</script>';
}

问题排查与解决办法

  • $post变量未正确初始化:自定义文章类型单页中,global $post可能在$post被赋值前就被调用,导致ID判断失效。改用get_queried_object()获取当前页面对象,更可靠:
$current_post = get_queried_object();
if ( $current_post && $current_post->ID == 1385 ) {
    // 原Schema代码逻辑
}
  • 页面ID验证错误:先确认目标页面的实际ID是否为1385。可以在模板中临时添加echo $post->ID;输出当前页面ID,验证是否与预期一致。

  • 代码执行时机不当:如果代码直接放在模板顶部,可能在WordPress完成页面查询前就执行了。建议将代码挂载到wp_footer钩子,确保页面对象已加载:

add_action('wp_footer', function() {
    $current_post = get_queried_object();
    if ( $current_post && $current_post->ID == 1385 ) {
        $arrJson = array(
            '@context' => 'https://schema.org/',
            '@type' => 'AggregateRating',
            "ratingValue" => "4.93",
            "bestRating" => "5",
            "ratingCount" => "18",
            "itemReviewed" => array(
                '@type' => 'Hospital',
                'name' => 'Practice Plus Group Hospital Barlborough',
                'telephone' => '0330 053 6443',
                "address" => array (
                    "@type" => "PostalAddress",
                    "streetAddress" => "2 Lindrick Way",
                    "addressLocality" => "Barlborough",
                    "addressRegion" => "Chesterfield",
                    "postalCode" => "S43 4XE",
                    "addressCountry" => "UK"
                ),
            ),
        );
        echo '<script type="application/ld+json">';
        echo json_encode($arrJson);
        echo '</script>';
    }
});
  • HTML转义问题:原代码中用&lt;替代<会导致输出的script标签被转义,虽不影响条件判断,但会让Schema无法被搜索引擎正确解析,直接使用<即可。

内容的提问来源于stack exchange,提问作者Ruth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:53:16