我想获得我的自定义图像大小的URL,以便有条件地注入它们。
(这在functions.php中)
首先,我删除了默认的裁剪尺寸,因为我从未使用过它们。
// remove all the default image sizes
function sgr_filter_image_sizes( $sizes) {
unset( $sizes[\'thumbnail\']);
unset( $sizes[\'medium\']);
unset( $sizes[\'large\']);
return $sizes;
}
add_filter(\'intermediate_image_sizes_advanced\', \'sgr_filter_image_sizes\');
然后定义我将使用的新尺寸。
// add custom image sizes
function add_custom_image_sizes() {
add_image_size ( \'small-screen\', 700, 350, true );
add_image_size ( \'medium-screen\', 1200, 600, true );
add_image_size ( \'large-screen\', 2000, 1000, true );
add_image_size ( \'extra-large-screen\', 3200, 1600, true );
}
add_action(\'init\', \'add_custom_image_sizes\');
然后在我的HTML/PHP中,我正在做这样的事情
<?php if ( has_post_thumbnail() ) { ?>
<?php $thisPostId = get_post_thumbnail_id(); ?>
<img src="some-blank-image-of-the-correct-ratio.png"
data-url-small="<?php echo wp_get_attachment_image_src( $thisPostId, \'small-screen\' ); ?>"
data-url-medium="<?php echo wp_get_attachment_image_src( $thisPostId, \'medium-screen\' ); ?>"
data-url-large="<?php echo wp_get_attachment_image_src( $thisPostId, \'large-screen\' ); ?>"
data-url-extra-large="<?php echo wp_get_attachment_image_src( $thisPostId, \'extra-large-screen\' ); ?>"
alt=\'\'>
<?php } else { ?>
<img src=\'http://placehold.it/1600x800/333/&text=No featured image yet\' alt=\'\'>
<?php } ?>
然后在我的JavaScript中,我可以根据一组情况选择使用白色URL。
我得到了一个软故障,它会返回每个的完整图像。
这位于单个customPostType页面上,不在循环中。
SO网友:sheriffderek
所以,我终于注意到我所做的是返回一个数组,并且我需要[0]
那个阵列的。代码有丑陋的一面,但它是有效的。
<?php
$thumb_id = get_post_thumbnail_id();
$small_screen = wp_get_attachment_image_src($thumb_id,\'small-screen\', true);
$medium_screen = wp_get_attachment_image_src($thumb_id,\'medium-screen\', true);
$large_screen = wp_get_attachment_image_src($thumb_id,\'large-screen\', true);
$extra_large_screen = wp_get_attachment_image_src($thumb_id,\'extra-large-screen\', true);
?>
-
<div class=\'container hero-w\'
data-background-large=\'<?php echo $large_screen[0]; ?>\'
data-background-extra-large=\'<?php echo $extra_large_screen[0]; ?>\'>
<div class=\'inner-w\'>
<div class=\'image-w hero\'>
<?php if ( has_post_thumbnail() ) { ?>
<img src="<?php echo get_template_directory_uri(); ?>/images/2x1.png"
data-image-small="<?php echo $small_screen[0]; ?>"
data-image-medium="<?php echo $medium_screen[0]; ?>"
data-image-large="<?php echo $large_screen[0]; ?>"
alt=\'\'>
<?php } else { ?>
<img src=\'http://placehold.it/1600x800/333/&text=No featured image yet\' alt=\'\'>
<?php } ?>
</div>
</div>
</div>