如何在content.php中设置条件隐藏空值的div.mostrasconto?
最优解决方案
核心思路是先获取折扣值并存储到变量中,通过条件判断仅在折扣值非空时,才输出包含折扣信息的.mostrasconto容器,同时避免重复调用函数提升效率。
修改后的代码如下:
<div class=imagen01> <?php sacconicase_post_thumbnail();?> <?php $author_discount = get_the_author_meta('discount', $post->post_author); if (!empty($author_discount)) { echo '<div class="mostrasconto"> -', $author_discount, '%</div>'; } ?> </div>
代码说明:
- 先将折扣值存入
$author_discount变量,减少重复调用get_the_author_meta的开销 - 使用
!empty()判断折扣值是否非空,确保只有当存在有效折扣值时才渲染折扣容器 - 输出内容时用字符串拼接简化写法,同时保留原有的格式(空格、减号、百分号)
内容的提问来源于stack exchange,提问作者Andrea Sacconi
相关产品推荐
相关产品推荐

