programing

동적 데이터를 표시하기 위한 for loop 만들기

codeshow 2023. 9. 14. 23:42
반응형

동적 데이터를 표시하기 위한 for loop 만들기

저는 현재 맞춤형 워드프레스 템플릿을 개발 중입니다.이 템플릿 내에서 특정 카테고리의 모든 게시물을 표시하려고 합니다. 일종의 제품 세그먼트로 간주합니다(판매 등은 금지).그래서 지금 제가 얻은 것은 ACF의 설정을 통해 모든 포스트 이미지와 제목을 모든 스타일링과 필터링으로 역동적으로 보여주는 것입니다.

제가 이루고 싶은 것은 (부트스트랩을 사용하여) 다음과 같은 결과입니다.

각 행에 4개의 열이 있지만 게시물이 4개 이상일 경우.(따라서 특정 카테고리의 두번째 또는 세번째 행이 있어야 할 때) 게시물을 보여주기 위한 축소 기능을 만듭니다 5 >.

그래서 몇 번의 시도 끝에, 가장 좋은 방법은 for loop을 만드는 것이고, 필터링과 결합하면 내가 만들고자 하는 뷰를 만들 것이라는 결론에 도달했습니다.안타깝게도 몇 가지 다른 방법을 시도한 후에, 저는 좀 막혔습니다.코드는 다음과 같습니다.

<div id="items">
<?php

    if (have_rows('products_category')) {

        while (have_rows('products_category')) : the_row();

        // Your loop code
        $title = get_sub_field('product_category_name');
        $slug = get_sub_field('product_category_slug');

        /* Start the filter categpries segment */
        $category = get_category_by_slug($slug);
        $filter_id = $category->term_id;
        $filters = array();
        var_dump($filters);
        array_push($filters, $filter_id);
        var_dump($filters);
        array_push($filters, 7);
        var_dump($filters);

        ?>
        <div id="items" class="row products margin-0 justify-content-between">
            <div class=" <?php echo $filter_id ?> ">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 padding-0 padding-b-10">
                    <h2><?php echo $title ?></h2>
                </div>
                <div class="col-lg-12 padding-0">
                    <div id="products" class="row products margin-0 justify-content-between">
                        <?php $argsNew = array(
                            'offset' => 0,
                            'category' => $filters,
                            'orderby' => 'date',
                            'order' => 'DESC',
                            'include' => '',
                            'exclude' => '',
                            'meta_key' => '',
                            'meta_value' => '',
                            'post_type' => 'post',
                            'post_mime_type' => '',
                            'post_parent' => '',
                            'author' => '',
                            'author_name' => '',
                            'post_status' => 'publish',
                            'posts_per_page' => -1,
                            'suppress_filters' => false,
                            'connected_items' => get_queried_object(),
                        );
                        $posts_array = get_posts($argsNew);
                        $number_posts = count($posts_array);
                        echo $number_posts;
                        $i = 0;
                        foreach ($posts_array as $post) : setup_postdata($post);
                        $i++;
                        if($i <= 4) {
                        ?>
                            <div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 margin-fix padding-s-15 padding-b-30 image_filter">
                                <?php echo get_the_post_thumbnail($post->ID, '', array('class' => 'img-responsive big_image products_image img_small')); ?>
                                <?php the_title(sprintf('<h2 class="text-center big_image_product_text products_text"><a href="%s" rel="bookmark">', esc_url(get_permalink())),
                                    '</a></h2>'); ?>
                                <?php

                                ?>
                            </div>
                            <?php
                            }
                                else if($i > 4) {
                                    ?>
                    </div>
                        <div class="row">
                            <button data-toggle="collapse" class="btn-collapse" data-target="#products_collapse_<?php echo $filter_id ?>">Show more</button>
                        </div>
                    <div id="products_collapse_<?php echo $filter_id ?>" class="row products collapse margin-0 justify-content-between">
                        <div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 margin-fix padding-s-15 padding-b-30 image_filter">
                            <?php echo get_the_post_thumbnail($post->ID, '', array('class' => 'img-responsive big_image products_image img_small')); ?>
                            <?php the_title(sprintf('<h2 class="text-center big_image_product_text products_text"><a href="%s" rel="bookmark">', esc_url(get_permalink())),
                                '</a></h2>'); ?>
                        </div>
                    </div>

                        <?php
                        }
                        endforeach;
                        wp_reset_postdata(); ?>
                        </div>
                    </div>
                </div>
        <?php
        endwhile;
        }
        else {
        // no rows found
            echo "nothing found!";
        }
        ?>
    </div>

갱신하다

포루프를 만들어 보았습니다.$number_posts그리고 카운트 방법이지만 슬프게도 시야가 심하게 망가졌습니다.그래서 제 질문은:

  1. for loop/counter를 만들어 표시되는 각 카테고리의 게시물 수를 계산합니다.
  2. 다음 결과에 대한 보기를 지정합니다.

-> 항목 1,2,3,4. 일렬로 놓으십시오. (1 1 1 1 1). if (4개 이상).항목을 5개 이상 배치합니다.붕괴된 블록 밑에.

예.

3가지 항목:

Normal view: 

1 1 1.

7개 항목:

보기 + 접기(

 1 1 1 1 
 -collapse button-
 1 1 1 
(more items)

)

누가 올바른 방향으로 보여주거나 이것을 도와줄 수 있습니까?미리 감사드립니다!

추신: 궁금한 사항은 아래 댓글로 문의해 주시기 바랍니다.

필드 가정products_category선택한 범주 ID 배열을 반환합니다. 이렇게 하면 작동합니다.

<div id="items">
<?php
    // Retrieve all product categories
    $terms = get_terms( 'product_cat' );
    // Retrieve chosen categories to display 
    $specified_cats = get_field( "products_category" );

    // Loop though product cats
    foreach ( $terms as $term ) {

        $filter_id = $term->term_id;
        // If the current product category id is not in the array 'specified_cats' just to the next iteration
        if(!in_array($filter_id, $specified_cats)){
            continue;
        }

        $title = $term->name;
        $slug = $term->slug;


       ?>
        <div id="items" class="row products margin-0 justify-content-between">
            <div class=" <?php echo $filter_id ?> ">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 padding-0 padding-b-10">
                    <h2><?php echo $title ?></h2>
                </div>
                <div class="col-lg-12 padding-0">
                    <div id="products" class="row products margin-0 justify-content-between">
                        <?php 
                        $argsNew = array (
                            'offset' => 0,
                            'orderby' => 'date',
                            'order' => 'DESC',
                            'post_type' => 'product',
                            'post_status' => 'publish',
                            'posts_per_page' => -1,
                            'product_cat'=> $term->name
                        ); 

                        $posts_array = get_posts($argsNew);
                        $number_posts = count($posts_array);
                        $i = 0;
                        foreach ($posts_array as $post) : setup_postdata($post);
                        $i++;
                        if($i <= 4) {
                        ?>
                            <div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 margin-fix padding-s-15 padding-b-30 image_filter">
                                <?php echo get_the_post_thumbnail($post->ID, '', array('class' => 'img-responsive big_image products_image img_small')); ?>
                                <?php the_title(sprintf('<h2 class="text-center big_image_product_text products_text"><a href="%s" rel="bookmark">', esc_url(get_permalink())),
                                    '</a></h2>'); ?>
                                <?php

                                ?>
                            </div>

                            <?php
                            }else if($i > 4) {
                                    ?>
                        <div class="row">
                            <button data-toggle="collapse" class="btn-collapse" data-target="#products_collapse_<?php echo $filter_id ?>">Show more</button>
                        </div>
                        <div id="products_collapse_<?php echo $filter_id ?>" class="row products collapse margin-0 justify-content-between">
                            <div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 margin-fix padding-s-15 padding-b-30 image_filter">
                                <?php echo get_the_post_thumbnail($post->ID, '', array('class' => 'img-responsive big_image products_image img_small')); ?>
                                <?php the_title(sprintf('<h2 class="text-center big_image_product_text products_text"><a href="%s" rel="bookmark">', esc_url(get_permalink())),
                                    '</a></h2>'); ?>
                            </div>
                        </div>
                        <?php
                        }
                        endforeach;
                        wp_reset_postdata(); ?>
                        <div class="clearfix"></div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
        <?php
    }

?>
</div>

코드가 테스트되고 작동합니다.모든 것이 제대로 작동하는지 확인하기 위해 부트스트랩까지 포함시켰습니다.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

언급URL : https://stackoverflow.com/questions/49571178/creating-a-for-loop-for-showing-dynamic-data

반응형