Support

Account

Home Forums Add-ons Repeater Field Getting instance and (sort of) ID of repeater field Reply To: Getting instance and (sort of) ID of repeater field

  • Hey Elliot,

    I’ve referenced this article quite a few times. This method has been very helpful but a case came up that this didn’t apply. I wanted to share my solution.

    Issue:
    Outputting the row ID can be problematic when using flexible content fields because a repeater can appear multiple times on the page, resulting in matching row IDs.

    Solution:
    Use PHPs built in random number generator to create a variable.

    Here’s a basic example for use in any project:

    <?php
    // generate random var for IDs, anchors, etc.
    $num = mt_rand ();
    $num_var = sprintf ($num);
    
    // echo random var
    echo $num_var;

    Here’s an example within a repeater field:

    <?php if( have_rows('repeater_field') ): ?>
      <?php while ( have_rows('repeater_field') ) : the_row(); ?>
    
        <?php
        // create random var id for backstretch
        $num = mt_rand ();
        $num_var = sprintf ($num); ?>
    
        <?php echo $num_var; ?>
    
      <?php endwhile; ?>
    <?php endif; ?>

    The number range can be altered for info here: http://www.php.net//manual/en/function.mt-rand.php

    Hope that helps someone!

    UPDATE

    I’ve found a few instances where my solutions above didn’t work. When special characters AND similar titles are involved there comes a time to get super specific.

    Here’s the combined solution that I’ve come up with from the research I’ve done.

    It strips out tags, shortens the output so long title URLs aren’t a problem, and add a row ID for similarly titled links.

    // Strip HTML Tags
    $anchor_var = strip_tags(get_sub_field('section_title'));
    
    // Clean up things like &
    $anchor_var = html_entity_decode($anchor_var);
    
    // Strip out any url-encoded stuff
    $anchor_var = urldecode($anchor_var);
    
    // Replace non-AlNum characters with space
    $anchor_var = preg_replace('/[^A-Za-z0-9]/', '', $anchor_var);
    
    // Replace Multiple spaces with single space
    $anchor_var = preg_replace('/ +/', ' ', $anchor_var);
    
    // Trim the string of leading/trailing space
    $anchor_var = trim($anchor_var);
    
    // Trim length of output
    $anchor_var_trim = substr($anchor_var,0,15);

    Here’s an example within a repeater field:

    <?php if( have_rows('repeater_field') ): $i = 0; ?>
      <?php while ( have_rows('repeater_field') ) : the_row(); $i++; ?>
    
        <?php echo $anchor_var_trim; ?>-<?php echo $i; ?>
    
      <?php endwhile; ?>
    <?php endif; ?>