codememo

PHP 루프:세 항목 구문 주위에 div를 추가합니다.

tipmemo 2023. 2. 8. 17:57
반응형

PHP 루프:세 항목 구문 주위에 div를 추가합니다.

워드프레스에서 루프를 사용하여 게시물을 출력합니다.3개씩 div 안에 넣고 싶어요.루프가 반복될 때마다 카운터를 사용하여 증분하고 싶지만 "$i가 3의 배수인 경우" 또는 "$i가 3-1의 배수인 경우"라는 구문을 알 수 없습니다.

$i = 1;
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // If is the first post, third post etc.
     if("$i is a multiple of 3-1") {echo '<div>';}

     // post stuff...

     // if is the 3rd post, 6th post etc
     if("$i is a multiple of 3") {echo '</div>';}

$i++; endwhile; endif;

어떻게 하면 될까요?고마워!

왜 다음을 하지 않는가?이렇게 하면 이 파일이 열리고 세 번째 게시물 이후에 닫힙니다.그런 다음 표시할 3의 배수가 없는 경우 끝 div를 닫습니다.

$i = 1;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // post stuff...

     // if multiple of 3 close div and open a new div
     if($i % 3 == 0) {echo '</div><div>';}

$i++; endwhile; endif;
//make sure open div is closed
echo '</div>';

혹시 모르실까 봐%는, 2 개의 번호가 분할된 후에, modus 연산자가 나머지를 반환하는 것입니다.

계수 연산자를 사용합니다.

if ( $i % 3 == 0 )

코드에서는 다음을 사용할 수 있습니다.

if($i % 3 == 2) {echo '<div>';}

그리고.

if($i % 3 == 0) {echo '</div>';}
$i = 1;
$post_count=$wp_query->found_posts;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // post stuff...

     // if multiple of 3 close div and open a new div
     if($i % 3 == 0 && $i != $post_count) {echo '</div><div>';} elseif($i % 3 == 0 && $i == $post_count){echo '</div>';}

$i++; endwhile; endif;

추가 div가 필요 없는 경우 다음을 사용할 수 있습니다.

 $i = 0;

 $post_count = $wp_query->found_posts;

 if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) :$wp_query->the_post();

 // If is the first post, third post etc.
 ( ($i%3) == 0 ) ? echo '<div>' : echo '';

 // post stuff...

 // if is the 3rd post, 6th post etc or after the last element

( $i == ($post_count - 1) || (++$i%3) == 0 )  ? echo '</div>' : 
echo '';

endwhile; endif;

언급URL : https://stackoverflow.com/questions/8947878/php-loop-add-a-div-around-every-three-items-syntax

반응형