css - 在 WordPress 中将特色图像设置为背景图像

标签 css wordpress

我一直在尝试将特色图像设置为我博客上的背景图像。这是我正在开发的单列自定义 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/

相关文章:

javascript - 如何将脚本排队以使用主题的 function.php 归档头?

wordpress - 在目录外使用 WordPress 用户详细信息

html - Firefox 3.6 中的 CSS 页面宽度 100% 滚动问题

javascript - 相对于浏览器窗口的宽度出现的动态下拉菜单

javascript - Angular js - 修复表格的标题

jquery - 尝试使用 jQuery 获取 css 左悬停属性

css - 我可以在不求助于完整内联代​​码的情况下使用基于 <use xlink> 的 SVG Sprite 修复跨浏览器的 CSS 问题吗?

javascript - 如何在wordpress中为类 "contentclass"的div设置ID?

php - 如何只显示一级子类别?

php - 如何在 wordpress 中设置站点 url/基本 url?