我有一个从数据库中提取信息的循环。如何在不使用jQuery的情况下将类添加到第一行?
while ( $query->have_posts() ) : $query->the_post();
if ( $keys = get_post_custom_keys() ) {
echo "<div class='card-prod'><span class='card-title'>";
echo the_title();
echo "</span>";
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt{0} || 'pricing' == $keyt || 'vehicleType' == $keyt || 'coverageRegion' == $keyt || 'locationType' == $keyt )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
echo "<span class='srch-val'>".apply_filters(" $value'n", $value)."</span>";
}
echo "'n";
echo '<img src="wp-content/themes/cafc/images/cards/dummy.png" />';
echo the_excerpt()."</div>";}
endwhile;
您需要一个计数器($i):
$i=0;
while ( $query->have_posts() ) : $query->the_post();
if ( $keys = get_post_custom_keys() ) {
echo "<div class='card-prod ".($i==0?'yourclasshere':'')."'><span class='card-title'>";
echo the_title();
echo "</span>";
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt{0} || 'pricing' == $keyt || 'vehicleType' == $keyt || 'coverageRegion' == $keyt || 'locationType' == $keyt )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
echo "<span class='srch-val'>".apply_filters(" $value'n", $value)."</span>";
}
echo "'n";
echo '<img src="wp-content/themes/cafc/images/cards/dummy.png" />';
echo the_excerpt()."</div>";
$i++;
}
endwhile;
保持计数?
$count = 0;
foreach ( (array) $keys as $key ) {
if ($count == 0)
{
//Do something
}
$count++;
}
如果你只想知道它是否是第一行,那么根据定义,布尔值而不是计数器是合适的。如果在任何一行上get_post_custom_keys()
的求值结果为false
,这将起作用。
<?php
$firstClassName = 'myclass'; // to be added to the first row
$firstRow = true;
while ( $query->have_posts() ) : $query->the_post();
if ( $keys = get_post_custom_keys() ) {
$additionalClass = $firstRow ? ' ' . $firstClassName : '';
echo "<div class='card-prod" . $additionalClass . "'><span class='card-title'>";
echo the_title();
echo "</span>";
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt{0} || 'pricing' == $keyt || 'vehicleType' == $keyt || 'coverageRegion' == $keyt || 'locationType' == $keyt )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
echo "<span class='srch-val'>".apply_filters(" $value'n", $value)."</span>";
}
echo "'n";
echo '<img src="wp-content/themes/cafc/images/cards/dummy.png" />';
echo the_excerpt()."</div>";
$firstRow = false;
}
endwhile;
?>