在中继器中获取具有特定值的特定行

时间:2018-09-17 15:20:53

标签: php wordpress advanced-custom-fields

我使用的Advanced Custom Fields repeater field每行有两个字段-imagemain_image

如果一行中的main_image选择了“是”,那么我希望它从该行中输出image。如果没有为任何行选择“是”,那么我只希望它选择第一个image

我要去哪里错了?

<?php if( have_rows( 'gallery' ) ): ?>
  <?php $rowcounter = 1;
  while( have_rows( 'gallery' ) ): the_row(); ?>
    <?php $image = get_sub_field( 'image' ); ?>

    <?php if(get_sub_field('main_image') == "Yes") { ?>

      <a href="#" class="slide">
        <img src="<?php echo $image[$rowcounter]['url']; ?>" alt="<?php echo $image[$rowcounter]['alt']; ?>">
      </a>

    <?php } else { ?>

      <a href="#" class="slide">
        <img src="<?php echo $image[1]['url']; ?>" alt="<?php echo $image[1]['alt']; ?>">
      </a>  

    <?php } ?>  


  <?php $rowcounter++;
  endwhile; ?>
<?php endif; ?>

我认为通过执行<?php echo $image[$rowcounter]['url']; ?>,它将从该行输出图像。

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试加载第一行,然后运行循环以有条件地更改特征图像值。

<?php 

if( have_rows( 'gallery' ) ) 
{
    // Load the first row and set the featured image
    the_row();

    $featured_image = get_sub_field( 'image' );

    while( have_rows( 'gallery' ) )
    { 
        the_row();

        // If a different image was set to be featured, set it and break out of loop
        if( get_sub_field('main_image') == "Yes" ) 
        {
            $featured_image = get_sub_field( 'image' );
            break;
        }
    }
?>
    <a href="#" class="slide">
        <img src="<?php echo $featured_image['url']; ?>" alt="<?php echo $featured_image['alt']; ?>">
    </a>  
<?php
}
?>

答案 1 :(得分:0)

您的$image var在每个while中重置-此行的迭代:<?php $image = get_sub_field( 'image' ); ?>。另外,您不必关闭php-标记只是为了在下一行再次打开它们,这只会使代码更难阅读。

<?php if ( have_rows( 'gallery' ) ) :

$images = [];
$i = 0;

while ( have_rows( 'gallery' ) ): the_row();

    $images[ $i ] = get_sub_field( 'image' );

    if ( get_sub_field( 'main_image' ) == "Yes" ) { ?>

        <a href="#" class="slide">
            <img src="<?php echo $images[ $i ][ 'url' ]; ?>" alt="<?php echo $images[ $i ][ 'alt' ]; ?>">
        </a>

    <?php } else { ?>

        <a href="#" class="slide">
            <img src="<?php echo $images[ 0 ][ 'url' ]; ?>" alt="<?php echo $images[ 0 ][ 'alt' ]; ?>">
        </a>

    <?php }

    ++$i;

endwhile;
endif; ?>

答案 2 :(得分:0)

获取所有行:

$rows = get_field('repeater' );

0将获得第一行,请记住计数从0开始:

$specific_row = $rows[YOUR_ROW_NUMBER];

获取子字段值:

$sub_field_value = $specific_row['SUB_FIELD_NAME'];