首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >减少和清理代码

减少和清理代码
EN

Stack Overflow用户
提问于 2014-01-14 22:32:40
回答 1查看 21关注 0票数 0

在wordpress category.php中,我有这样的代码:

代码语言:javascript
复制
if ( is_category('cat-1') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-1' , 'posts_per_page' => 3 ) ) ;
}

if ( is_category('cat-2') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-2' , 'posts_per_page' => 3 ) ) ;
}

if ( is_category('cat-3') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-3' , 'posts_per_page' => 3 ) ) ;
}


while ( $the_query->have_posts() ) : $the_query->the_post();
...
endwhile; wp_reset_postdata(); 

如何简化代码?我有30个类别,太多的条件句是不理想的…

EN

回答 1

Stack Overflow用户

发布于 2014-01-15 00:55:46

如果您知道类别的确切数量,可以尝试使用for循环:

代码语言:javascript
复制
for ($x=0; $x<=30; $x++) {
    if ( is_category('cat-' . $x) ) { $the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-' . $x , 'posts_per_page' => 3 ) ) ; }
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21116133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档