2017-10-19 1 views
0

나는 foreach를 사용하여 The Loop 외부의 게시물을 통해 루프해야하는 상황이 있습니다.

다음 루프는 잘 작동하지만 코드를 DRY로 유지하기 위해 실제로 같은 코드를 마이그레이션하면 문제가 발생합니다. 템플릿 코드는 특정 $ post 요소 (예 : 축소판, 제목 등)를 반복합니다. 다른 $ post 요소 (예 : 발췌 부분)에 대한 예상 정보를 반환합니다.

함수 또는 템플릿 코드 내에서 $ post를 사용하는 방법에 대해 필자가 놓치거나 잘못 이해하고있는 부분이 분명히 있지만,이 것을 이해할 수는 없습니다.

모든 설명이 훌륭합니다.

원본 코드 :

function get_grid(){ 
$posts = get_field('featured_projects', 'user_'.get_post()->post_author); 

if($posts){ 
    $current_index = 0; 
    $grid_columns = 3; 

    foreach ($posts as $post){ 

    if(0 === ($current_index ) % $grid_columns){ 
     echo '<div class="row archive-grid" data-equalizer>'; 
    } 

    setup_postdata($post); 

    get_template_part('parts/loop', 'custom-grid'); 

    if(0 === ($current_index + 1) % $grid_columns 
     || ($current_index + 1) === 3){ 
      echo '</div>'; 
     } 

    $current_index++; 

    } 
    wp_reset_postdata(); 

} 
} 

루프 - 사용자 정의 그리드 템플릿 코드

<div class="large-4 medium-4 columns panel" data-equalizer-watch> 

<article id="post-<?php the_ID(); ?>" <?php post_class(''); ?> 
role="article"> 

<?php if(has_post_thumbnail()): ?> 
    <section class="archive-grid featured-image" itemprop="articleBody" style="background-image: url('<?php 
    echo esc_url(get_the_post_thumbnail_url($post->ID, 'medium')); 
    ?>');"> 
    </section> 
<?php endif; ?> 

<header class="article-header"> 
    <h3 class="title"> 
    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3> 
    <?php get_template_part('parts/content', 'byline'); ?> 
</header> 

<section class="entry-content" itemprop="articleBody"> 
    <?php the_excerpt(); ?> 
</section> 
:

$posts = get_field('featured_projects', 'user_'.$post->post_author); 

if($posts){ 
     $current_index = 0; 
     $grid_columns = 3; 

    foreach ($posts as $post){ 

     if(0 === ($current_index ) % $grid_columns){ 
      echo '<div class="row archive-grid" data-equalizer>'; 
     } 

     setup_postdata($post); 

     get_template_part('parts/loop', 'custom-grid'); 

     if(0 === ($current_index + 1) % $grid_columns 
      || ($current_index + 1) === 3){ 
        echo '</div>'; 
      } 

     $current_index++; 

    } 
    wp_reset_postdata(); 
} 

기능으로 리팩토링

답변

1

다른 함수는 루프가 함수 내에있을 때 기대하는 $post을받지 못합니다. $post 변수는 해당 함수 내에 "존재"합니다.

그냥 전역에 $post 변수를 넣어하는 것입니다 해결하기

한 가지 간단한 방법 :

function get_grid(){ 
    global $post; 
    $posts = get_field('featured_projects', 'user_'.get_post()->post_author); 
    /* all the other code that works fine outside 
     a function should work fine inside too now */ 
} 
관련 문제