我正在尝试获取我正在构建的 WordPress 主题的主页,以根据 3 个可能的背景图像更改刷新时的背景图像。
每张图片都被视为具有标题、链接、文本等的更大“案例研究”的一部分。 案例研究字段是通过主页上的自定义元框创建的。 (我用它来简化元框创建过程:https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress)。
长话短说,客户希望主页上的3个案例研究有相应的背景图片。这就是我没有使用特色图片功能的原因,因为每个背景都带有特定的元数据。
问题是,我不知道如何获取所选背景图片的元 ID 并使用它来设置背景 CSS。
这是我目前所拥有的:
/**
* Home Page Case Randomizer
*/
$GLOBALS['_home_case_number'] = rand(1, 3);
function home_case_number() {
if ( is_front_page() ) : // checks whether this is the home page
// get the meta image
$attachment_image = get_post_meta( get_the_ID(), '_home_case_background_' . $_home_case_number, true );
这就是我感到困惑的地方。以上返回适当的 image.jpg
文件。我如何修改它以使用下面的代码?
以下代码改编自http://s2webpress.com/responsive-featured-image-function-in-wordpress-themes/ ,我想用它来确保我响应式地提供图像。
// store the image sizes in an array
$img_sizes = array( 'thumbnail', 'medium', 'large', 'full' );
// grab the URL for each image size and store in a variable
foreach ( $img_sizes as $img_size ) {
${ 'img_src_' . $img_size } = wp_get_attachment_image_src( $attachment_image, $img_size );
}
echo '<style type="text/css">
.featured-image {
width: 100%;
min-height:350px;
background-image: url(' . esc_url( $img_src_medium[0] ) . ');
}
@media screen and ( min-width: 400px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_large[0] ) . ');
}
}
@media screen and ( min-width: 1000px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_full[0] ) . ');
}
}
</style>';
endif;
};
add_action( 'wp_head', 'home_case_number' );
那么我是否可以通过获取背景图像的元 ID 来解决这个问题?还是附件ID?我现在也不知道该怎么做。
非常感谢任何帮助!
最佳答案
我想通了!
1) CMB“插件”通过在其末尾添加“_id”将附件 ID 另存为另一个元键,因此我使用它来获取附件 ID,并且 2)我有可变范围问题。一旦我在我的函数中调用我的全局变量,事情就开始工作了。这是最终代码:
/**
* Home Page Case Randomizer
*/
$GLOBALS['_home_case_number'] = rand(1, 3);
function home_case_number() {
global $_home_case_number;
if ( is_front_page() ) : // checks whether this is the home page
// get the attachment thumbnail ID
$attachment_image = get_post_meta( get_the_ID(), '_home_case_background_' . $_home_case_number . '_id', true );
// store the image sizes in an array
$img_sizes = array( 'thumbnail', 'medium', 'large', 'full' );
// grab the URL for each image size and store in a variable
foreach ( $img_sizes as $img_size ) {
${ 'img_src_' . $img_size } = wp_get_attachment_image_src( $attachment_image, $img_size );
}
echo '<style type="text/css">
.featured-image {
width: 100%;
min-height:350px;
background-image: url(' . esc_url( $img_src_medium[0] ) . ');
}
@media screen and ( min-width: 400px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_large[0] ) . ');
}
}
@media screen and ( min-width: 1000px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_full[0] ) . ');
}
}
</style>';
endif;
};
add_action( 'wp_head', 'home_case_number' );
希望这会帮助其他人。
关于php - 在 WordPress 中从自定义元设置背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20176470/