2017-10-19 83 views
0

我有一种情况,需要使用foreach循环遍历The Loop之外的帖子。

但是,当我将几乎相同的代码迁移到函数中(以保持代码干燥)时,以下循环可以正常工作:问题发生:模板代码重复某些$ post元素(例如缩略图,标题等)返回其他$ post元素的期待信息(如摘录)。

显然我在这里丢失或误解了如何在函数或模板代码中使用$ post,但是,我无法弄清楚这一点。

任何澄清将是伟大的。

原始代码:

$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(); 
} 

重构的功能:

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> 

回答

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 */ 
}