我一直在尝试将特色图像设置为我博客上的背景图像。这是我正在开发的单列自定义 WordPress 主题。
我的想法是类似medium.com和blog.pickcrew.com
你们能帮我得到它吗?
非常感谢!
最佳答案
您可以尝试以下代码片段。
将其保存到文件/wp-content/plugins/featured-image-background/featured-image-background.php
并激活它:
<?php
/**
* Plugin Name: Featured Image Background
* Description: Featured image as background for single posts
* Plugin URI: http://stackoverflow.com/q/23388561/2078474
*/
function so_23388561_wp_head()
{
if ( is_single() )
{
if ( has_post_thumbnail( get_the_ID() ) )
{
$image = array_shift(
wp_get_attachment_image_src(
get_post_thumbnail_id( get_the_ID() ),
'full'
)
);
printf( '<style>
body {
background-image: url("%s") !important;
background-size: cover;
}
</style>',
$image
);
}
}
}
add_action( 'wp_head', 'so_23388561_wp_head' );
您可能想使用 body
之外的其他 CSS 选择器,也许是 div#background
?
一般情况下,我使用 get_queried_object_id()
在循环外获取帖子 ID,但 get_the_ID()
在这种情况下应该可以工作。
我们使用 wp_head
Hook ,因此请确保您的主题具有 wp_head()
函数。
希望您可以根据需要进行修改。
关于css - 在 WordPress 中将特色图像设置为背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23388561/