【问题标题】:Why get_post_meta not returning JSON?为什么 get_post_meta 不返回 JSON?
【发布时间】:2025-12-08 15:00:02
【问题描述】:

我正在尝试使用 get_post_meta 和自定义字段来填充 JSON-ld。注意* JSON 中的信息仅用于测试目的。

自定义字段名称:架构
自定义字段值:

<script type="application/ld+json">
{
 "@context": "http://schema.org",
 "@type": "LocalBusiness",
 "address": {
   "@type": "PostalAddress",
   "addressLocality": "Example Town",
   "addressRegion": "Essex",
   "streetAddress": "123 Example Street"
 },
 "description": "A super shop that sells everything at super low prices.",
 "name": "Super Shop",
 "telephone": "01234567890"
}
</script>

get_post_meta PHP:

?><!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">

<?php wp_head(); ?>
<?php
global $post;
$schema = get_post_meta($post->ID, 'schema', true);
if(!empty($schema)) {
    echo $schema;
}
?>
</head>

我将 PHP 插入到主题 header.php 文件中,就在结束 &lt;/head&gt; 标记之前。

更新,清除缓存,刷新,没有任何反应。关于我在这里做错了什么有什么想法吗?

【问题讨论】:

  • 你的意思是“我没有看到页面上的任何东西”……就像script元素的情况一样……?
  • 是的,脚本没有填充到页面中。
  • 如果您 echo get_the_ID(); 是您要从中获取 post_meta 的正确帖子 ID 吗?
  • 代码看起来不错,您确定设置了元数据并且您检查了正确的页面吗?
  • 代码工作没有任何错误。确保 meta_key 是正确的,帖子有那个 meta

标签: php wordpress jsonschema


【解决方案1】:

由于我看不到您的所有代码,我将假设您不在 WordPress 循环中,问题是 get_the_ID() 仅返回 WordPress 循环中当前项目的帖子 ID。使用以下内容引用当前页面/帖子。

global $post;
$schema = get_post_meta($post->ID, 'schema', true);

【讨论】:

  • @BrianCampbell 将其发布在原始问题中。据我所知,问题是您需要像我在回答中所写的那样引用 global $post。
  • 对不起,第一次用户在格式化评论时遇到了困难。
  • 添加到原始问题
  • @BrianCampbell 检查 $post->ID 返回一个值,然后通过使用诸如 phpmyadmin 之类的工具浏览 post_meta 表来检查您的 post_meta 是否存在于数据库中。