【问题标题】:What's wrong with my relationship loop?我的关系循环出了什么问题?
【发布时间】:2015-01-09 15:32:30
【问题描述】:

我在使用 Wordpress 中的高级自定义字段的关系循环时遇到问题。

第一个帖子显示完美,但它应该再执行一个帖子,但事实并非如此。

谁能看到我的代码有什么问题?

<?php $posts = get_field('produkter'); if( $posts ): ?>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>

<div class="produkt">
<?php the_title(); ?>
<?php the_content(); ?>

<?php $posts = get_field('fil'); if( $posts ): ?>

<div id="filer">
<div id="topsection" class="laddahem"><div class="topborder"></div>
<h2>Ladda hem</h2>
</div><!-- #top -->

<div class="filhuvud">
    <div class="filtyp">Filtyp</div>
    <div class="fildatum">Datum</div>
    <div class="filstorlek">Filstorlek</div>
</div><!-- .filhuvud -->

<div class="filholder">

<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>

<?php $attachment_id = get_field('filen');
$url = wp_get_attachment_url( $attachment_id );
$title = get_the_title( $attachment_id );

// hämta filstorleken
$filesize = filesize( get_attached_file( $attachment_id ) );
$filesize = size_format($filesize, 1);

$filetype = strtolower(pathinfo($url, PATHINFO_EXTENSION)); ?>

<div class="fil <?php echo $filetype; ?>">
    <div class="filtyp"><a target="_blank" href="<?php echo $url; ?>" ><?php the_title(); ?></a></div>
    <div class="fildatum"><?php the_time('Y-m-d'); ?></div>
    <div class="filstorlek"><?php echo $filesize; ?></div>
</div><!-- .fil -->

<?php endforeach; ?>
<?php wp_reset_postdata(); ?>

</div><!-- .filholder -->

</div><!-- #filer --> 

<?php endif; ?>

</div><!-- .produkt -->

<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

【问题讨论】:

  • 就在你打电话给get_field('fil')之前,做一个wp_reset_postdata
  • @Anand,不幸的是,这根本没有帮助。
  • 在调用get_field('fil') 之后,执行var_dump($posts) 并查看它是否包含所需的数据。
  • @Anand,它输出了大量的数据...
  • 在同一数据中尝试检查您希望看到的帖子是否存在。

标签: php wordpress foreach advanced-custom-fields


【解决方案1】:

解决方案是将另一个 foreach 循环更改为:

<?php $files = get_field('fil'); if( $files ): ?>
<?php foreach( $files as $post): ?>
<?php setup_postdata($post); ?>

这使它完全按照我想要的方式工作。

【讨论】:

  • 根据我上面的评论,我写了更多关于出了什么问题的解释以及作为答案的解决方案。
  • 这个答案不完整。请参阅我上面的答案,了解@HenricÅkesson 试图在这里解释的完整答案。
【解决方案2】:

您的问题是,在循环外定义 $posts 变量后,您将其覆盖在循环内。

解决方案是将您的第二个 $posts 变量重命名为其他名称,以便您的总体循环如下所示:

  <?php $posts = get_field('produkter'); ?>

  <?php if( $posts ): ?>
    <?php foreach( $posts as $post): ?>


      <?php $files = get_field('fil'); //RENAMED THIS VARIABLE?>
      <?php if( $files ): ?>

         <?php foreach( $files as $file): ?>

               <?php //Main body of markup and other fun stuff ?>

         <?php endforeach; //end $files foreach ?>

      <?php endif; //end $files if ?>

     <?php endforeach; //end $posts foreach ?>
  <?php endif; //end $posts if ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多