我正在使用Wordpress API作为我的后端CMS与无头的React前端。我需要设置的最后一部分是社交Open Graph Meta标签。我正在使用NPM包react-meta-tags并试图了解如何将WP中的服务器端呈现传递给客户端组件。 docs详细介绍了基于节点的服务器渲染,但我无法将其转换为我的Wordpress后端。
有没有人用WP / Headless React构建实现OG标签?
您必须使用来自wordpress的动态数据通过API调用填充元标记。
这是一个通过slug获取特定帖子的示例(该概念对于其他数据也是如此):
componentDidMount() {
fetch(`YOUR_WP_DOMAIN/wp-json/wp/v2/posts?slug=YOUR_POST_SLUG&_embed`)
.then(response => {
return response.json();
})
.then(data => {
this.setState({post: data[0]});
})
.catch(function(e) {
console.log(e);
});
}
此时,您可以使用刚刚获取的数据填充所需的元标记:
<MetaTags>
<title>{this.state.post.title.rendered}</title>
<meta property="og:title" content={this.state.post.title.rendered} />
<meta property="og:image" content={post._embedded['wp:featuredmedia'][0].media_details.sizes.full.source_url} />
</MetaTags>
希望这有点帮助。快乐的编码!