在我的 WordPress 主题的自定义模板中,我有大约 20 多个 li 标签元素,其中 html 代码相同但值不同。我正在为每个元素创建单独的条件。
是否可以设置此代码的循环,以便我不应该为每个 li 标记创建一个单独的条件并减少我的 html 代码。
<?php $user_birthday = get_post_meta(get_the_ID(), 'user_birthday', true); ?>
<?php if(!empty($user_birthday)) { ?>
<li>
<span class="min-w-[100px] mr-2 inline-block font-bold"
>Birthday:</span
><span class="text-slate-500"><?php echo $user_birthday; ?></span>
</li>
<?php } ?>
<?php $user_age = get_post_meta(get_the_ID(), 'user_age', true);
if(!empty($user_age)) { ?>
<li>
<span class="min-w-[100px] mr-2 inline-block font-bold"
>Age:</span
><span class="text-slate-500"><?php echo $user_age; ?></span>
</li>
<?php } ?>
您可以循环播放内容
<?php
$user_birthday = get_post_meta(get_the_ID(), 'user_birthday', true);
$user_age = get_post_meta(get_the_ID(), 'user_age', true);
$items = [
'Birthday' => $user_birthday,
'Age' => $user_age
];
foreach ($items as $label => $value) {
if (!empty($value)) {
echo "<li><span class=\"min-w-[100px] mr-2 inline-block font-bold\">$label:</span><span class=\"text-slate-500\">$value</span></li>";
}
}
?>