这几乎完美地解决了我的一个问题:How do I add the featured image to the_content after the first paragraph?
但是,如果没有特征图像,代码仍会输出空白<img src alt title>
在第一段之后,创建一个空白。
有什么想法我可以修改这个代码,所以它会检查if 有一个特色图片,如果有,就把它放在第一段之后——但如果没有特色图片,就什么都不做了?
如果你能帮忙的话,请提前多谢!
这几乎完美地解决了我的一个问题:How do I add the featured image to the_content after the first paragraph?
但是,如果没有特征图像,代码仍会输出空白<img src alt title>
在第一段之后,创建一个空白。
有什么想法我可以修改这个代码,所以它会检查if 有一个特色图片,如果有,就把它放在第一段之后——但如果没有特色图片,就什么都不做了?
如果你能帮忙的话,请提前多谢!
你想要的has_post_thumbnail
.
add_filter( \'the_content\', insert_featured_image, 20 );
function insert_featured_image( $content ) {
global $post;
if (has_post_thumbnail($post->ID)) {
$content = preg_replace( "/<\\/p>/", "</p>" . get_the_post_thumbnail($post->ID, \'post-single\'), $content, 1 );
}
return $content;
}
注:以上代码来自post referenced in the OP, 但在has_post_thumbnail
有条件的我还必须补充global $post;
避免“未定义变量”Notices
s、 或者,你可以离开$post
引用输出为has_post_thumbnail
和get_the_post_thumbnail
将承担全球$post
(这就是为什么原始代码可以工作的原因)。add_filter( \'the_content\', insert_featured_image, 20 );
function insert_featured_image( $content ) {
if (has_post_thumbnail()) {
$content = preg_replace( "/<\\/p>/", "</p>" . get_the_post_thumbnail(null, \'post-single\'), $content, 1 );
}
return $content;
}
这里是wordpress的新成员。动作/过滤器的概念本身并不难理解。令我不知所措的是大量可用的操作和过滤器。当我阅读教程/指南时,他们会说“只需将此功能添加到wp\\U head操作或after\\U setup\\u主题”。如果没有这些教程,我究竟如何知道将该函数与该操作挂钩?作为一个初学者,我怎么会知道什么是合适的操作?有没有关于如何导航的建议?谢谢