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>