【问题标题】:Accessing $post in function scope在函数范围内访问 $post
【发布时间】: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


    【解决方案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 */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 2017-09-24
      • 2021-10-16
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      相关资源
      最近更新 更多