添加按页面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转义问题:原代码中用
<替代<会导致输出的script标签被转义,虽不影响条件判断,但会让Schema无法被搜索引擎正确解析,直接使用<即可。
内容的提问来源于stack exchange,提问作者Ruth
相关产品推荐
相关产品推荐

