我希望将当前单个帖子的内容加载到og:description元属性中,但是\'. $content .\'
没有输出任何内容?
这是我的标题。php
if (is_single()) {
$content = get_the_content();
$desc=\'<meta property="og:description" content="\'. $content .\'" />\';
echo $desc;
}
可能是什么问题?我希望将当前单个帖子的内容加载到og:description元属性中,但是\'. $content .\'
没有输出任何内容?
这是我的标题。php
if (is_single()) {
$content = get_the_content();
$desc=\'<meta property="og:description" content="\'. $content .\'" />\';
echo $desc;
}
可能是什么问题?get_the_content()
必须在里面the loop, 在标题中。php您可以这样做(不要忘记将内容替换为属性):
if (is_single()) {
while (have_posts()) {
the_post();
$content = get_the_content();
$desc=\'<meta property="og:description" content="\'. esc_attr($content) .\'">\';
echo $desc;
}
}
或者更好,在你的功能上。php钩住wp\\U头部动作;此外,我建议使用摘录而不是内容作为描述符。(注意使用global$post和setup_postdata). add_action( \'wp_head\', \'my_wp_head\' );
function my_wp_head() {
if (is_single()) {
$post_id = get_queried_object_id():
$excerpt = get_the_excerpt( $post_id );
$desc = \'<meta property="og:description" content="Blabla\'. esc_attr( $excerpt ) .\'">\';
echo $desc;
}
//More stuff to put in <head>
}
有关详细信息,请参阅codex页get_the_content()
:
Description
检索帖子内容。(必须在循环中使用)
重点»Must be used in a Loop«。
<小时>
Edit:
要提供可能的解决方案,您可以使用get_post()
, 对于页面和帖子,如下图所示,获取循环外的帖子内容。$post_id = get_queried_object_id();
$post_obj = get_post( $post_id );
$content = $post_obj->post_content;
<小时>Update:
彼得·奈特(PeterKnight)对Differences between using get_post() and WP_Query(). 我不能全部复制,但基本上可以归结为:性能和可用数据量。一个简短而不完全的总结可能是:一方面WP_Query
你也有元数据,而不是get_post
, 但另一方面WP_Query
有四个数据库查询,而有一个数据库查询使用get_post
. 因此,肯定有一些差异需要考虑,阅读本文了解更多信息,哪种方法是正确的取决于手头的实际用例需要什么。