优化PHP中的循环



我确实创建了一个循环,用正确的颜色显示正确的图像。但我认为代码可以更小更快。但我不知道如何使代码更智能。

有人能给我小费或帮助我吗?

<?php
// Setup your custom query
$args = array( 'post_type' => 'product', 'posts_per_page' => 7);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php echo get_permalink( $loop->post->ID ) ?>" class="d-block w-100">
<h2><?php the_title(); ?></h2>
<img src="<?php the_post_thumbnail_url(); ?>" class="img-fluid">
<?php
$brand_terms = get_the_terms($post, 'pa_kleur');
$brand_string = ''; // Reset string
foreach ($brand_terms as $term) : ?> <div style="display: block; margin-bottom: 50px;"><?php
if (($term->name) == 'Roze') {
echo '<div style="width: 20px; height: 20px; background-color: pink;" class="roze-kleur"></div>';
$variations = $product->get_available_variations();
foreach ( $variations as $key => $value ) {
?>
<?php if ($value['attributes']['attribute_pa_kleur'] == 'roze') { ?>
<li>
<span><?php echo $value['image']['url']; }?></span>
</li></div>
<?php
}
}
if (($term->name) == 'Grijs') {
echo '<div style="width: 20px; height: 20px; background-color: grey;" class="grijze-kleur"></div>';
$variations = $product->get_available_variations();
foreach ( $variations as $key => $value ) {
?>
<?php if ($value['attributes']['attribute_pa_kleur'] == 'grijs') { ?>
<li>
<span><?php echo $value['image']['url']; }?></span>
</li></div>
<?php
}
}
endforeach;
?>
</a><br>
<?php endwhile; wp_reset_query(); // Remember to reset ?>

谢谢你抽出时间!

我认为这种方式有点简化和可扩展,因为如果您需要更多的条件,只需添加elseif或switch案例即可使用功能。

<?php
// Setup your custom query
$args = array( 'post_type' => 'product', 'posts_per_page' => 7);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php echo get_permalink( $loop->post->ID ) ?>" class="d-block w-100">
<h2><?php the_title(); ?></h2>
<img src="<?php the_post_thumbnail_url(); ?>" class="img-fluid">
<?php
$brand_terms = get_the_terms($post, 'pa_kleur');
$brand_string = ''; // Reset string
foreach ($brand_terms as $term) : ?> <div style="display: block; margin-bottom: 50px;"><?php
$act = 1;
if ($term->name=='Roze') {
$color = 'pink';
$class = 'roze';
}else{
$color = 'grey';
$class = 'grijze';
}
$variations = $product->get_available_variations();
foreach ( $variations as $key => $value ) {
if ($value['attributes']['attribute_pa_kleur'] == 'roze') {
?>
<div style="width: 20px; height: 20px; background-color: <?=$color?>;" class="<?=$class?>-kleur"></div>
<li>
<span><?php echo $value['image']['url']; }?></span>
</li>
</div>
<?php
}
}
endforeach;
?>
</a><br>
<?php endwhile; wp_reset_query(); // Remember to reset ?>

希望它对你有用!

最新更新