【发布时间】:2017-06-18 22:54:29
【问题描述】:
我正在学习 WordPress,并通过一些默认主题尝试了解它们的工作原理。我在 TwentySeventeen 主题 (twentyseventeen/template-parts/page/content-front-page.php) 中遇到了这一部分,这让我很困惑:
<?php if ( has_post_thumbnail() ) :
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'twentyseventeen-featured-image' );
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
$thumbnail_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'twentyseventeen-featured-image' );
// Calculate aspect ratio: h / w * 100%.
$ratio = $thumbnail_attributes[2] / $thumbnail_attributes[1] * 100;
?>
<div class="panel-image" style="background-image: url(<?php echo esc_url( $thumbnail[0] ); ?>);">
<div class="panel-image-prop" style="padding-top: <?php echo esc_attr( $ratio ); ?>%"></div>
</div><!-- .panel-image -->
<?php endif; ?>
我还是一个新手程序员,所以也许我遗漏了一些明显的东西,但我不明白为什么会发生以下两件事:
- 为什么创建了 $post_thumbnail_id 变量但从未使用过?为什么不立即创建它,而不是不断调用 get_post_thumbnail_id( $post->ID )?
- $thumbnail 和 $thumbnail_attributes 是一样的,对吧?那么为什么要同时创建两者呢?
这不是更有意义吗:
<?php if ( has_post_thumbnail() ) :
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
$thumbnail = wp_get_attachment_image_src( $post_thumbnail_id, 'twentyseventeen-featured-image' );
// Calculate aspect ratio: h / w * 100%.
$ratio = $thumbnail[2] / $thumbnail[1] * 100;
?>
<div class="panel-image" style="background-image: url(<?php echo esc_url( $thumbnail[0] ); ?>);">
<div class="panel-image-prop" style="padding-top: <?php echo esc_attr( $ratio ); ?>%"></div>
</div><!-- .panel-image -->
<?php endif; ?>
我创建了一个子主题并使用上面的代码而不是原来的代码,一切正常。我想我只是在摸索为什么原始开发人员会这样编码,从学生的角度来看,我希望得到一些见解。
【问题讨论】:
-
是的。提交给core.trac.wordpress.org。
标签: php wordpress wordpress-theming