如果您使用WordPress的自适应图像插件,只需使用最大的图像为所有视口宽度制作一个内联css,然后它就可以在服务器上完成所有工作。您对标记不做任何操作,但在Adaptive Images插件设置中输入断点,以便将小图像提供给小设备等等。
如果使用自适应图像,则可能是:
/**
*
* Background Image from Post Image using Adaptive Images Plugin for WordPress
* @since 1.0.0
* Credits: TwentyFifteen WordPress theme adjacent pagination
*
*/
function the_other_idea_good_heavens_change_this_function_name() {
global $post;
if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image
$theme_handle = \'visionary\'; //the theme handle used for the main style.css file
//image
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'super-huge-image\' );
//css
$css = \'.banner-image { background-image: url(\' . esc_url( $image[0] ) . \'); } \';
//minify
$css = str_replace( array("\\r\\n", "\\r", "\\n", "\\t", \' \', \' \', \' \'), \'\', $css );
//add it
wp_add_inline_style( $theme_handle, $css );
}
add_action( \'wp_enqueue_scripts\', \'the_other_idea_good_heavens_change_this_function_name\', 99 );
这就是我所做的(在我开始使用Adapative图像之前)。
add_image_size();
在本例中,我使用了三种尺寸:小、中、大,然后重新生成缩略图。
/**
*
* Background Image from Post Image
* @since 1.0.0
* Credits: TwentyFifteen WordPress theme adjacent pagination
*
*/
function yourprefix_responsive_mobile_first_background_images() {
global $post;
if ( ! has_post_thumbnail( $post->ID ) ) return; //exit if there is no featured image
$theme_handle = \'visionary\'; //the theme handle used for the main style.css file
$property = \'.banner-image\'; //the property
$css = \'\';
//small image
$small_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'my-small-image-size\' );
$small_style = \'
\' . $property . \' { background-image: url(\' . esc_url( $small_img[0] ) . \'); }
\';
$css .= $small_style;
//medium image
$medium_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'my-medium-image-size\' );
$medium_style = \'
\' . $property . \' { background-image: url(\' . esc_url( $medium_img[0] ) . \'); }
\';
$css .= \'@media (min-width: 1000px) { \'. $medium_style . \' }\';
//large image
$large_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'my-large-image-size\' );
$large_style = \'
\' . $property . \' { background-image: url(\' . esc_url( $large_img[0] ) . \'); }
\';
$css .= \'@media (min-width: 1700px) { \'. $large_style . \' }\';
//minify
$css = str_replace( array("\\r\\n", "\\r", "\\n", "\\t", \' \', \' \', \' \'), \'\', $css );
//add it
wp_add_inline_style( $theme_handle, $css );
}
add_action( \'wp_enqueue_scripts\', \'yourprefix_responsive_mobile_first_background_images\', 99 );