我有一个简单的主页,其中包含4个不同类别的内容。为此,我编写了4个不同的WP\\u查询,只有类别名称在更改(结果是WP\\u查询名称等)。
有没有更有效的方法?有没有可能将WP\\u查询放在foreach循环中?或者有没有更好的方法来重命名变量,而不是编写4次WP\\u查询?
下面是一个代码示例。这重复了4次,只更改了“category\\u name”以及一些变量名:
<?php
$fashion_cat = array(
\'category_name\' => \'fashion\',
\'posts_per_page\' => 4,
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'post__not_in\' => $already_posted,
\'category__not_in\' => $private_categories
);
$fashion_query = new WP_Query( $fashion_cat );
if ( $fashion_query->have_posts() ):
$i = 0;
while ( $fashion_query->have_posts() ):
$fashion_query->the_post();
$images = get_field( \'gallery\' );
if ( $images ):
$i++;
?>
<?php if ( $i == 1 ): ?>
<div class="col-1">
<div class="img-ctnr">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
</div>
<div class="col-2">
<?php elseif ( $i == 2 || $i == 3 ): ?>
<div class="img-ctnr-small">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
<?php elseif ( $i == 4 ): ?>
<div class="img-ctnr-med">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
<?php
endif;
endif;
endwhile;
endif;
wp_reset_postdata();
?>
这是我尝试将其放入foreach循环中,但它只调用一次:
<?php
$home_cats = array( \'fashion\', \'beauty\', \'lifestyle\' );
foreach ( $home_cats as $key ):
echo $key;
$key_cat = array(
\'category_name\' => $key,
\'posts_per_page\' => 4,
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'post__not_in\' => $already_posted,
\'category__not_in\' => $private_categories
);
$key_query = new WP_Query( $key_cat );
if ( $key_query->have_posts() ):
$i = 0;
while ( $key_query->have_posts() ):
$key_query->the_post();
$images = get_field( \'gallery\' );
if ( $images ):
$i++;
if ( $i == 1 ): ?>
<div class="col-1">
<div class="img-ctnr">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
</div>
<div class="col-2">
<?php elseif ( $i == 2 || $i == 3 ): ?>
<div class="img-ctnr-small">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
<?php elseif ( $i == 4 ): ?>
<div class="img-ctnr-med">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $images[0][\'url\'];?>"></a>
<?php top_note(); ?>
</div>
<?php
endif;
endif;
endwhile;
endif;
wp_reset_postdata();
endforeach;
?>