我试图在worpdpress循环中使用switch语句来更改div上的类,但是递增计数器($IntCounter)似乎没有在循环中触发:
<?php
global $intCounter;
$intcounter = 0;
query_posts('category_name=clients&posts_per_page=3&tag=new-work');
if(have_posts()) : while(have_posts()) : the_post();
$intcounter++;
switch ($intcounter){
case 1:
$ThisPostCSSClass ="new-work-post span-7 colborder ";
break;
case 2:
$ThisPostCSSClass ="new-work-post span-8 colborder ";
break;
case 3:
$ThisPostCSSClass ="new-work-post span-7 last";
break;
default:{
$ThisPostCSSClass="noclass";
}
}
?>
<div class="<?php echo $ThisPostCSSClass;?>" id="<?php the_ID(); ?>">
<div class="">
<?php the_content(); ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
</div> <!-- .post -->
<?php endwhile;endif; ?>我是不是漏掉了什么明显的东西?谢谢
发布于 2011-03-31 05:37:14
您正在获取全局$intCounter;,但是设置和递增$intcounter;并不确定这就是问题所在,因为您正在正确地初始化$intcounter=0;并递增它。所以这只意味着global $intCounter;是不必要的。
发布于 2011-03-31 05:42:01
我有一种感觉,这和你使用global有关。通常,它被用在一个作用域中,告诉它您希望使用变量的全局定义版本,而不是局部版本。
我继续用大括号重做了代码块的结构(为了美观,请取笑我),并删除了全局关键字。试着尝试一下这个模块,看看它对你是否有效:
<?php
query_posts('category_name=clients&posts_per_page=3&tag=new-work');
if(have_posts()) {
$intcounter = 0; // Moved this to within the IF block
while(have_posts()){
// If you did want to use the "global" keyword, you'd probably use it here:
// global $intcounter;
the_post();
$intcounter++;
switch ($intcounter){
case 1:
$ThisPostCSSClass ="new-work-post span-7 colborder ";
break;
case 2:
$ThisPostCSSClass ="new-work-post span-8 colborder ";
break;
case 3:
$ThisPostCSSClass ="new-work-post span-7 last";
break;
default: // Curly braces not required here.
$ThisPostCSSClass="noclass";
} // Switch
?>
<div class="<?php echo $ThisPostCSSClass;?>" id="<?php the_ID(); ?>">
<div class="">
<?php the_content(); ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
</div> <!-- .post -->
<?php
} // While
} // If
?>发布于 2011-03-31 05:41:18
您的全局$intcounter中有一个大写的C,但是您正在递增并打开$intCounter。这会初始化两个不同的变量。switch语句和循环在其他方面都工作得很好。
https://stackoverflow.com/questions/5492662
复制相似问题