Support

Account

Home Forums Add-ons Repeater Field Difficulty sorting on repeater sub-field

Solving

Difficulty sorting on repeater sub-field

  • I’ve looked through this page and *sort of* have things working, but just not quite.

    It’s listing all objects, but only shows one <h2> for all of them. What am I missing? I need one grouping of <h2></h2>

    for each sub_field titled ‘position’.

    So, it would look something like:

    <h2>Position 1</h2>

    • Document #1 for position 1
    • Document #2 for position 1
    • Document #3 for position 1

    <h2>Position 2</h2>

    • Document #1 for position 2
    • Document #2 for position 2
    • Document #3 for position 2

    This is my code thus far:

    <?php // get repeater field data
    $repeater = get_field('house_forms');
    
    // vars
    $order = array();
    
    // populate order
    foreach( $repeater as $i => $row ) {
        $order[ $i ] = $row['position'];
    }
    
    // multisort
    array_multisort( $order, SORT_DESC, $repeater );
    
    // loop through repeater
    if( $repeater ): ?>
    <h2><?php echo $row['position']; ?></h2>
    <ul class="forms">
    
        <?php foreach( $repeater as $i => $row ): ?>
        <li class="form"><?php echo $row['form_name']; ?>
            <a href="<?php echo $row['document']; ?>" target="_blank">Download</a><?php if( $row['online'] ): ?> | <a href="<?php echo $row['online']; ?>">Fill out online</a><?php endif; ?>
        <?php endforeach; ?>
    
    </ul>
    <?php wp_reset_postdata(); ?>
  • Hi @brotsky_pixie

    That’s because you put the code outside of the loop. It should be something like this:

    // loop through repeater
    if( $repeater ):
    
    // initialize the position for later use
    $position = '';
    ?>
    
    <ul class="forms">
    
        <?php foreach( $repeater as $i => $row ): ?>
            
            
            <?php
            // check if the current postion is changed
            if( $position != $row['position'] ){
                
                // set the current position 
                $position = $row['position'];
                ?>
                
                <h2><?php echo $row['position']; ?></h2>
                
            <?php } ?>
            
            
            <li class="form"><?php echo $row['form_name']; ?>
            <a href="<?php echo $row['document']; ?>" target="_blank">Download</a><?php if( $row['online'] ): ?> | <a href="<?php echo $row['online']; ?>">Fill out online</a><?php endif; ?>
        <?php endforeach; ?>
    
    </ul>
    <?php wp_reset_postdata(); ?>

    Because this is more related to PHP, kindly visit their community for further support.

    I hope this helps 🙂

  • Ahhhhh…I see. Thank you. And I’m sorry I didn’t realize it was a purely PHP problem. I appreciate the help.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.