Что не так с моей петлей отношений?

У меня проблема с циклом отношений с расширенными настраиваемыми полями в 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; ?>

1

Решение

Ваша проблема в том, что вы перезаписываете $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 ?>
0

Другие решения

Решением было изменить другой цикл foreach на этот:

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

Это заставило его работать именно так, как я этого хотел.

-1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector