在 PHP 中分配 Img Class
Assign Img Class in PHP
我创建了以下函数,用于使用 ACF 收集将用作主页背景图像的图像。一周中的每一天都会有不同的图像。我想对图像使用延迟加载,但我不知道如何在这种情况下分配图像 class。感谢您的任何建议。
function my_custom_background() {
if ( ! is_front_page() ) {
return;
}
$img_id = get_field( strtolower( date( 'l' ) ) );
echo "<style>\n";
// Large desktops.
$img = wp_get_attachment_image_src( $img_id, 'large_desktop_background' );
echo "body {\n";
echo sprintf( "\tbackground-image: url(%s);\n", $img[0] );
echo "}\n";
// Small desktops.
$img = wp_get_attachment_image_src( $img_id, 'small_desktop_background' );
echo "@media (max-width: 1199px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Tablets.
$img = wp_get_attachment_image_src( $img_id, 'tablet_background' );
echo "@media (max-width: 991px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Mobile.
$img = wp_get_attachment_image_src( $img_id, 'phone_background' );
echo "@media (max-width: 767px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
echo "</style>\n";
}
add_action( 'wp_head', 'my_custom_background' );
您可以使用过滤器将 类 添加到 body 标签。
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'class-name' ) );
} );
我创建了以下函数,用于使用 ACF 收集将用作主页背景图像的图像。一周中的每一天都会有不同的图像。我想对图像使用延迟加载,但我不知道如何在这种情况下分配图像 class。感谢您的任何建议。
function my_custom_background() {
if ( ! is_front_page() ) {
return;
}
$img_id = get_field( strtolower( date( 'l' ) ) );
echo "<style>\n";
// Large desktops.
$img = wp_get_attachment_image_src( $img_id, 'large_desktop_background' );
echo "body {\n";
echo sprintf( "\tbackground-image: url(%s);\n", $img[0] );
echo "}\n";
// Small desktops.
$img = wp_get_attachment_image_src( $img_id, 'small_desktop_background' );
echo "@media (max-width: 1199px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Tablets.
$img = wp_get_attachment_image_src( $img_id, 'tablet_background' );
echo "@media (max-width: 991px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Mobile.
$img = wp_get_attachment_image_src( $img_id, 'phone_background' );
echo "@media (max-width: 767px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
echo "</style>\n";
}
add_action( 'wp_head', 'my_custom_background' );
您可以使用过滤器将 类 添加到 body 标签。
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'class-name' ) );
} );