如何在HP中调整图片尺寸?代码无法生效问题求助
问题原因
你当前的写法错误在于,the_post_thumbnail()函数会直接输出完整的<img>标签,你把height="130" width="150"拼在它前面,最终会生成无效的HTML结构——这些尺寸属性根本没被添加到<img>标签内部,所以尺寸调整完全不生效。
解决方法
方法1:直接传入自定义尺寸参数
WordPress的the_post_thumbnail()支持直接传入尺寸数组或自定义属性数组,这是最简洁的写法:
<a href="<?php echo esc_url( $image_popup_url ); ?>" class="image-popup"> <?php the_post_thumbnail( array(150, 130), array( 'class' => 'optional-class' ) ); ?> </a>
第一个参数array(150, 130)对应宽度和高度,第二个数组可额外添加class等其他属性。
方法2:用get_the_post_thumbnail()手动拼接属性
如果需要更灵活的属性控制,改用get_the_post_thumbnail()(它返回HTML字符串而非直接输出),再替换或添加目标属性:
<a href="<?php echo esc_url( $image_popup_url ); ?>" class="image-popup"> <?php $thumbnail_html = get_the_post_thumbnail( get_the_ID(), 'colormag-featured-image' ); // 将尺寸属性插入img标签开头 $thumbnail_html = str_replace( '<img', '<img width="150" height="130"', $thumbnail_html ); echo $thumbnail_html; ?> </a>
方法3:注册自定义图像尺寸(推荐长期使用)
如果这个尺寸会在多处复用,建议在主题的functions.php中注册专属图像尺寸:
function register_custom_thumbnail_size() { add_image_size( 'custom-small-thumbnail', 150, 130, true ); // 第三个参数true表示强制裁剪图片到指定尺寸 } add_action( 'after_setup_theme', 'register_custom_thumbnail_size' );
注册完成后,直接调用这个自定义尺寸即可:
<a href="<?php echo esc_url( $image_popup_url ); ?>" class="image-popup"> <?php the_post_thumbnail( 'custom-small-thumbnail' ); ?> </a>
注意:注册新尺寸后,需用Regenerate Thumbnails类插件重新生成已有图片的缩略图,新上传的图片会自动生成该尺寸。
方法4:用CSS强制控制尺寸
如果不需要修改<img>标签的原生属性,也可以通过CSS直接设置显示尺寸:
.image-popup img { width: 150px; height: 130px; object-fit: cover; /* 可选,保持图片比例不变,裁剪超出部分 */ }
内容的提问来源于stack exchange,提问作者jacques
相关产品推荐
相关产品推荐

