【发布时间】:2017-10-19 19:30:41
【问题描述】:
我有一种情况需要使用 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();
}
}
Loop-custom-grid 模板代码
<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>
【问题讨论】:
标签: php wordpress loops templates