我正在为一系列的12门课设置一个查询,每个课将持续一周。上午和晚上各有一节课。我将在模板中使用两个不同的循环来分解这些循环。每节课有三个项目供学生选择,为了使问题更加复杂,这些课程将重复一次。第一次发生在六月,第二次发生在七月。下面的代码似乎正在运行。我可以先筛选项目,然后无论是6月会议还是7月会议,显示整个帖子或仅显示注册链接。
我的问题是,我必须为每个循环重复if(in\\u category(\'16\')中的代码三次(使用不同的cat编号),才能使其正常工作。我觉得我应该能够用某种foreach或while语句来代替它,该语句将迭代类别id的数组。比如if(in\\u category(array(\'16\',17\',18\')),然后以某种方式遍历每一个,一次一个执行下面的代码。我猜我必须将当前的cat id分配给一个变量,并将其传递到get\\u term\\u by中,这样如果可能的话,我的计数器仍然可以工作。非常感谢您的帮助!
<?php
$args = array(
\'post_type\' => \'summerartcamp\',
\'cat\' => 15, //This is for the Morning Group - I\'ll have a second loop for the Afternoon Group
\'order\' => \'ASC\',
\'meta_key\' => \'_expiration-date\',
\'orderby\' => \'meta_value\'
);
$the_query = new WP_Query( $args );
?>
<?php if (have_posts()) : ?>
<?php while ( $the_query->have_posts()) : $the_query->the_post(); ?>
<?php if (in_category(\'16\')) { // Can I replace this with some sort of array of categories that I can iterate through? ?>
<?php $postsInCat = get_term_by(\'id\', \'16\', \'category\');
$postsInCat = $postsInCat->count;
if($postsInCat == 2) { // If the number of posts is two I only need to show the button for the second post
if (in_category(\'22\')) {
echo \'This is the first post\';
echo "<h2>" . get_the_title() . "</h2>";
}
if (in_category(\'23\')) {
echo \'This is the second post\';
}
}
if($postsInCat == 1) { // If there is only one post I\'ll give the full post
echo "<h2>" . get_the_title() . "</h2>";
} ?>
<?php } ?>
<?php
endwhile; endif;
?>
最合适的回答,由SO网友:TheDeadMedic 整理而成
In short, yes!
$args = array(
\'post_type\' => \'summerartcamp\',
\'cat\' => 15, //This is for the Morning Group - I\'ll have a second loop for the Afternoon Group
\'order\' => \'ASC\',
\'meta_key\' => \'_expiration-date\',
\'orderby\' => \'meta_value\'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() /* Make sure you use the method, not the global function have_posts(), which only applies to the main loop */ ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
foreach ( array( 16, 17, 18 ) as $the_cat_id ) {
if ( in_category( $the_cat_id ) ) {
$postsInCat = get_term_by( \'id\', $the_cat_id, \'category\' );
if ( $postsInCat->count == 2 ) { // If the number of posts is two I only need to show the button for the second post
if (in_category( 22 ) ) {
echo \'This is the first post\';
echo "<h2>" . get_the_title() . "</h2>";
}
if ( in_category( 23 ) ) {
echo \'This is the second post\';
}
} else if ( $postsInCat->count == 1 ) { // If there is only one post I\'ll give the full post
echo "<h2>" . get_the_title() . "</h2>";
}
}
}
}
}