我正在尝试编写自己的代码来填充JSON-LD Schema代码(我不想依赖于插件)。
对于Wordpress帖子,关键的模式元素之一是作者数据。所以我使用get_the_author_meta()函数来访问它。
当它在wp_footer动作中触发时,它可以很好地工作,但在wp_head中触发时,它会出现空洞。
我已经在astra主题和twentytwentyone主题中检查了这一点。
我偷了这段代码只是为了演示,它是twitter OG卡,而不是Schema,但实际上是一样的。对不起,我想不起来我是在什么地方找到的。
在functions.php中:
function my_twitter_cards() {
if (is_singular()) {
global $post;
$twitter_user = get_the_author_meta('nickname'); #This is the element that works in wp_footer but not in wp_head, all the other fields seem to work.
$twitter_url = get_permalink();
$twitter_title = get_the_title();
$twitter_excerpt = get_the_excerpt();
$twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
$twittercard_thumb = $twittercard_image[0];
if (!$twittercard_thumb) {
$twittercard_thumb = 'https://www.example.com/default-image.png';
}
if ($twitter_user) {
echo '<meta name="twitter:creator" value="@' . esc_attr($twitter_user) . '" />' . "\n";
}
echo '<meta name="twitter:card" value="summary" />' . "\n";
echo '<meta name="twitter:url" value="' . esc_url($twitter_url) . '" />' . "\n";
echo '<meta name="twitter:title" value="' . esc_attr($twitter_title) . '" />' . "\n";
echo '<meta name="twitter:description" value="' . esc_attr($twitter_excerpt) . '" />' . "\n";
echo '<meta name="twitter:image" value="' . esc_url($twittercard_thumb) . '" />' . "\n";
echo '<meta name="twitter:site" value="@mhthemes" />' . "\n";
}
}
add_action('wp_head', 'my_twitter_cards'); #swap this out for wp_footer to see the difference.我的理论是,当在header中调用时,它不能访问循环,但这不能解释为什么填充特定于post的数据(即固定链接、标题等),而不是get_the_author_meta数据。
现在我可以使用它,如果我只是填充页脚,在这个应用程序中它是可以的,但一些东西需要在标题中,所以我想弄清楚为什么它不能像预期的那样工作。
提前谢谢你!
发布于 2021-04-18 15:39:48
get_the_author_meta()接受两个可选参数:
get_the_author_meta(string $field = '', int|false $user_id = false)其中$field是要检索的用户字段(默认值为''),$user_id是用户ID (默认值为false)
在循环中使用时,不需要指定用户ID,它缺省为当前的帖子作者。如果在循环之外使用,则必须指定用户ID。
您可以在循环之外获取当前的帖子作者ID,然后使用它来获取所需的作者字段,如下所示:
global $post;
$post_id = $post->ID;
$post_author_id = get_post_field('post_author', $post_id);
$twitter_user = get_the_author_meta('nickname', $post_author_id);注意,上面的示例使用了全局$post,因为您已经在代码中使用了它,否则我将使用get_queried_object_id()在循环之外获取post ID:
$post_id = get_queried_object_id();
https://stackoverflow.com/questions/67144437
复制相似问题