How do I make this PHP code a loop or more dynamic?
The [sample] code below seems like it could be better in a loop or something to make it more dynamic. The only thing that changes is the _xx and _xxyy in the field/variable name. How can I improve this so I don't have to write 20 if statements?:
<?php if (get_custom_field('itinerary_title_02'开发者_StackOverflow社区)):?>
<div id="itinerary_entry">
<h2><?php print_custom_field('itinerary_title_02'); ?></h2>
<p><?php print_custom_field('itinerary_content_02'); ?></p>
<p class="accommodation_name"><?php print_custom_field('itinerary_acc_nme_02'); ?></p>
<p class="accommodation_desc"><?php print_custom_field('itinerary_acc_dsc_02'); ?></p>
<?php if (get_custom_field('itinerary_photo_0201')):?>
<div><img src="<?php print_custom_field('itinerary_photo_0201'); ?>"></div>
<?php endif;?>
</div>
<?php endif;?>
<?php if (get_custom_field('itinerary_title_03')):?>
<div id="itinerary_entry">
<h2><?php print_custom_field('itinerary_title_03'); ?></h2>
<p><?php print_custom_field('itinerary_content_03'); ?></p>
<p class="accommodation_name"><?php print_custom_field('itinerary_acc_nme_03'); ?></p>
<p class="accommodation_desc"><?php print_custom_field('itinerary_acc_dsc_03'); ?></p>
<?php if (get_custom_field('itinerary_photo_0301')):?>
<div><img src="<?php print_custom_field('itinerary_photo_0301'); ?>"></div>
<?php endif;?>
</div>
<?php endif;?>
<?php if (get_custom_field('itinerary_title_04')):?>
<div id="itinerary_entry">
<h2><?php print_custom_field('itinerary_title_04'); ?></h2>
<p><?php print_custom_field('itinerary_content_04'); ?></p>
<p class="accommodation_name"><?php print_custom_field('itinerary_acc_nme_04'); ?></p>
<p class="accommodation_desc"><?php print_custom_field('itinerary_acc_dsc_04'); ?></p>
<?php if (get_custom_field('itinerary_photo_0401')):?>
<div><img src="<?php print_custom_field('itinerary_photo_0401'); ?>"></div>
<?php endif;?>
</div>
<?php endif;?>
Thanks in advance!
<?php
for($i=2 ; $i<5 ; $i++ ){
$titleNum = sprintf("%02d", $i);
if (get_custom_field('itinerary_title_'.$titleNum)) {
?>
<div id="itinerary_entry">
<h2><?php print_custom_field('itinerary_title_'.$titleNum); ?></h2>
<p><?php print_custom_field('itinerary_content_'.$titleNum); ?></p>
<p class="accommodation_name"><?php print_custom_field('itinerary_acc_nme_'.$titleNum); ?></p>
<p class="accommodation_desc"><?php print_custom_field('itinerary_acc_dsc_'.$titleNum); ?></p>
<?php if (get_custom_field('itinerary_photo_'.$titleNum.'01')){ ?>
<div><img src="<?php print_custom_field('itinerary_photo_'.$titleNum.'01'); ?>"></div>
<?php } ?>
</div>
<?php }
}
?>
You can replace your duplicate code with a for
loop.
<?php
for ( $i = 2; $i <= 4; $i++) { // Modify this range as needed
$dynamic_value = ($i < 10) ? "0$i" : $i; // Prefix the value with a '0' when necessary
if ( get_custom_field("itinerary_title_$i")):?>
<!-- HTML and PHP goes here. Replace each hard-coded number with '$i' -->
<?php
}
?>
精彩评论