itsource

다중 스타일링 디브로 php를 루프하는 방법

mycopycode 2023. 10. 24. 21:19
반응형

다중 스타일링 디브로 php를 루프하는 방법

저는 WP 테마를 작업하고 있는데 여기서 설명할 수 없는 특정 작업을 우연히 수행하게 되었습니다. 하지만 여기서 스크린샷을 보여주면 문제를 이해할 수 있을 것입니다.

우선 게시물은 아래 이미지를 참조해주시기 바랍니다.div구조.

enter image description here

그것은 HTML로부터의 실제 디자인이고, 구체적으로 a 내부의 처음 2개의 게시물입니다.div그리고 다른 내부의 세번째 포스트.div아래 스크린샷처럼

enter image description here

이해가 안 되면 댓글 달아주세요.

문제는 동일한 구조와 디자인을 유지함으로써 어떻게 그것을 동적으로 루프할 것인가 하는 것입니다.

그리고 여기 아래 내 코드가 있습니다.

<div class="row justify-content-center">
    <div class="col-xl-3 col-lg-6 col-md-6">
        <?php
        while($projects_array->have_posts()):
            $projects_array->the_post();

            $idd = get_the_ID();
            $terms = wp_get_post_terms(get_the_ID(), 'project_cat');

            $output = array();
            if ($terms) {
                $i = 1;
                foreach ($terms as $term) {
                    if($i == 1):
                        $output[] = '<span class="tag-'.$i.'">'.$term->name.'</span>';
                        $id[] = $term->term_id ;
                    endif;
                    $i++;
                }
            }

            if ( class_exists('ACF') && get_field('choose_link_type') == 1 ) {
                $post_link = get_the_permalink();
            } else {
                $post_link = get_field('external_link');
            }
            ?>
                <div class="single-portfolio-box">
                    <?php if(has_post_thumbnail()): ?>
                        <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_post_thumbnail_caption(); ?>">
                    <?php endif; ?>
                    <div class="content">
                        <h3><a href="<?php echo esc_url( $post_link ); ?>"><?php the_title(); ?></a></h3>
                        <?php echo join( ' ', $output ); ?>
                    </div>
                </div>
        <?php endwhile; ?>
        <?php wp_reset_query(); ?>
    </div>
</div>

미리 감사드립니다.

인덱스를 생성하고 다음과 같은 세 가지 경우에 출력을 수행할 수 있습니다.

$index = 1;
while ($projects_array->have_posts()) {
    $modulo3 = $index % 3;
    //Initialize your values
    if (($modulo3 === 1) || ($modulo3 === 0)) {
        //Display the wrapper div's start
    }
    //Display the actual post content
    if (($modulo3 % 3 === 2) || ($modulo3 === 0)) {
        //Display the wrapper div's end
    }
    $index++;
}
if ($index % 3 === 2) {
    //Display the wrapper div's end
}

나는 당신의 구조를 조사하지 않았습니다. 당신이 나보다 그것을 더 잘 알고 있기 때문입니다.그러나 현재 상태를 나타내는 숫자 값이 있으면 포장지의 어떤 부분을 표시해야 하는지 알 수 있습니다.3회 반복의 각 주기는 다음과 같이 구성됩니다.

  • 1단계 : 포장지의 시작과 게시물 표시
  • 2단계 : 게시물과 포장지 끝을 표시
  • 3단계: 포장지의 시작, 게시물, 포장지의 끝을 표시합니다.

지금까지, 좋아요.반복 횟수가 3의 배수일 경우 각 단계에서 두 개의 게시물이 포장지로 포장되고 세 번째 게시물이 포장지로 포장됩니다.그러나 게시물의 수가 세 개의 배수가 아닌 경우 마지막 세 개 그룹에서 처리해야 하는 특수한 경우가 발생합니다.표시할 게시물의 수가 3n + 2개(n은 자연수)인 경우 마지막 그룹은 두 개의 게시물로 구성되며, 이 게시물은 사이클 내부의 포장지로 잘 포장됩니다.그러나 표시할 게시물의 수가 3n + 1(n은 자연수)이면 마지막 단계에서 포장지를 열고 게시물을 표시했습니다.그런 경우에는 주기가 끝난 직후에 포장지를 닫아야 합니다.

사용합니다.$post_index우리가 어떤 인덱스를 열고 닫을 것인지 다루기 위해서입니다.그래서 기본적으로 우리는 다음과 같이 할 것입니다.

  • 오픈 디바 1, 3, 4, 6, 7, 9...
  • 2, 3, 5, 6, 8, 9에 근접한 디바...

우리는 이 일을 처리합니다.$post_index % 3. 번역된 조건은 다음과 같습니다.

  • div open div :$post_index % 3 == 1 || $post_index % 3 == 0
  • close div :$post_index % 3 == 2 || $post_index % 3 == 0

그리고 저는.$is_open디브가 열려있는 경우 처리하기 위해 열린 디브 상태를 추적합니다. 그리고 게시물 길이가 가까운 조건과 일치하기에 충분하지 않기 때문에 닫히지 않습니다.그러면 저희가 수동으로 닫겠습니다.

<div class="row justify-content-center">

        <?php
        $post_index = 0;
        $is_open = false;
        while($projects_array->have_posts()):

            $post_index++;
            // open div to wrap posts by grouped 1, 3, 4, 6, 7, 9...
            if ($post_index % 3 == 1 || $post_index % 3 == 0) {
                echo '<div class="col-xl-3 col-lg-6 col-md-6">';
                $is_open = true;
            }

            $projects_array->the_post();

            $idd = get_the_ID();
            $terms = wp_get_post_terms(get_the_ID(), 'project_cat');

            $output = array();
            if ($terms) {
                $i = 1;
                foreach ($terms as $term) {
                    if($i == 1):
                        $output[] = '<span class="tag-'.$i.'">'.$term->name.'</span>';
                        $id[] = $term->term_id ;
                    endif;
                    $i++;
                }
            }

            if ( class_exists('ACF') && get_field('choose_link_type') == 1 ) {
                $post_link = get_the_permalink();
            } else {
                $post_link = get_field('external_link');
            }
            ?>
            <div class="single-portfolio-box">
                <?php if(has_post_thumbnail()): ?>
                    <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_post_thumbnail_caption(); ?>">
                <?php endif; ?>
                <div class="content">
                    <h3><a href="<?php echo esc_url( $post_link ); ?>"><?php the_title(); ?></a></h3>
                    <?php echo join( ' ', $output ); ?>
                </div>
            </div>

            <?php
                // close wrapped div if post index is 2, 3, 5, 6, 8, 9...
                if ($post_index % 3 == 2 || $post_index % 3 == 0) {
                    $is_open = false;
                    echo '</div>';
                }
            ?>

        <?php endwhile; ?>
        <?php wp_reset_query(); ?>

    <?php
        // close div if it's closed (happens when post count is 1, 4, 7,...)
        if ($is_open) {
            echo '</div>';
        }
    ?>

</div>

제 사이트에서 실행해봤는데 완벽하게 작동합니다.데모 HTML 구조

<div class="row justify-content-center">
<div class="col-xl-3 col-lg-6 col-md-6">
    <?php $j = 0;
    while($projects_array->have_posts()):
        $projects_array->the_post();

        $idd = get_the_ID();
        $terms = wp_get_post_terms(get_the_ID(), 'project_cat');

        $output = array();
        if ($terms) {
            $i = 1;
            foreach ($terms as $term) {
                if($i == 1):
                    $output[] = '<span class="tag-'.$i.'">'.$term->name.'</span>';
                    $id[] = $term->term_id ;
                endif;
                $i++;
            }
        }

        if ( class_exists('ACF') && get_field('choose_link_type') == 1 ) {
            $post_link = get_the_permalink();
        } else {
            $post_link = get_field('external_link');
        }
        ?>
        <?php if(in_array($j,['2','3','5'])) echo '</div><div class="col-xl-3 col-lg-6 col-md-6">';?>
            <div class="single-portfolio-box">
                <?php if(has_post_thumbnail()): ?>
                    <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_post_thumbnail_caption(); ?>">
                <?php endif; ?>
                <div class="content">
                    <h3><a href="<?php echo esc_url( $post_link ); ?>"><?php the_title(); ?></a></h3>
                    <?php echo join( ' ', $output ); ?>
                </div>
            </div>
    <?php $j++; endwhile; ?>
    <?php wp_reset_query(); ?>
</div>

값을 삽입해야 하는 템플릿이 있으므로 값을 만들고 삽입하는 것이 가장 좋습니다.따라다니듯이

          <?php
            $posts = array();
            $i = 0;
            while($projects_array->have_posts()):
                $projects_array->the_post();
    
                $idd = get_the_ID();
                $terms = wp_get_post_terms(get_the_ID(), 'project_cat');
    
                $output = array();
                if ($terms) {
                    $i = 1;
                    foreach ($terms as $term) {
                        if($i == 1):
                            $output[] = '<span class="tag-'.$i.'">'.$term->name.'</span>';
                            $id[] = $term->term_id ;
                        endif;
                        $i++;
                    }
                }
    
                if ( class_exists('ACF') && get_field('choose_link_type') == 1 ) {
                    $post_link = get_the_permalink();
                } else {
                    $post_link = get_field('external_link');
                }
    
                        if(has_post_thumbnail()) {
                                $posts[$i]["img"] = '<img src="'.get_the_post_thumbnail_url().'" alt="'.get_the_post_thumbnail_caption.'">';
                            }else{
                                $posts[$i]["img"] = "";
                            }
                            $posts[$i]["content"] = '<h3><a href="'.esc_url( $post_link ).'">'.get_the_title().'</a></h3>';
                            $posts[$i]["output"] = join( ' ', $output );

endwhile;
wp_reset_query();
                        
               ?>
                        

            
    <div class="row justify-content-center">
        <div class="col-xl-3 col-lg-6 col-md-6">
                    <div class="single-portfolio-box">
                        <?php echo $posts[0]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[0]["content"]; 
                                        echo $posts[0]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
                    <div class="single-portfolio-box">
                        <?php echo $posts[1]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[1]["content"]; 
                                        echo $posts[1]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
        </div>
        <div class="col-xl-3 col-lg-6 col-md-6">
                    <div class="single-portfolio-box">
                        <?php echo $posts[3]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[3]["content"]; 
                                        echo $posts[3]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
    
        </div>
        <div class="col-xl-3 col-lg-6 col-md-6">
                    <div class="single-portfolio-box">
                        <?php echo $posts[4]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[4]["content"]; 
                                        echo $posts[4]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
                    <div class="single-portfolio-box">
                        <?php echo $posts[5]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[5]["content"]; 
                                        echo $posts[5]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
        </div>
        <div class="col-xl-3 col-lg-6 col-md-6">
                    <div class="single-portfolio-box">
                        <?php echo $posts[6]["img"]; ?>
                        <div class="content">
                                    <?php 
                                        echo $posts[6]["content"]; 
                                        echo $posts[6]["output"]; 
                                    
                                    ?>
                        </div>
                    </div>
    
        </div>
    
    </div>

언급URL : https://stackoverflow.com/questions/69175621/how-to-loop-php-with-multiple-styling-div

반응형