Support

Account

Home Forums Add-ons Repeater Field Orderby title instead of foreach Reply To: Orderby title instead of foreach

  • Hi @gleenk, lucky you I have a lazy Sunday and therefore I had some time to check out your code.

    First of all, please change the “Return Value” on your “Relationship” field from “Post Objects” to “Post IDs”, this way we get a nice array of all the WP_Post->IDs instead of the full WP_Post objects. See the screenshot attached for more info.

    So this brings me to the code:

    <?php if ( get_field( 'schede_prodotti' ) ): ?>
    <table class="product-list simple-list">
        <?php while( has_sub_field( 'schede_prodotti' ) ): ?>
        <tr>
            <td class="title">
            <?php
                /**
                 * Get the IDs
                 *
                 * Returns an array of the IDs of the posts
                 * selected using the Relationship field.
                 *
                 * @see Screenshot: Change return value from Post Objects to Post IDs
                 * @var array
                 */
                $ids = get_sub_field( 'relazione_prodotti' );
    
                /**
                 * Prepare the get_posts arguments
                 *
                 * With the 'orderby' => 'ttile' we accomplish the goal of having the
                 * products ordered by name instead of drag and drop.
                 *
                 * @see http://codex.wordpress.org/Template_Tags/get_posts#Parameters
                 * @var array
                 */
                $args = array(
                    'post__in'  => $ids,    // Use the ids from above
                    'order'     => 'ASC',   // Order
                    'orderby'   => 'title'  // Field to order the posts by
                );
    
                /**
                 * Query the Posts
                 *
                 * @var array
                 */
                $posts = get_posts( $args );
    
                if ( $posts ) :
    
                    foreach ( $posts as $post ) : setup_postdata( $post ); ?>
    
                        <span><?php the_title(); ?></span><?php
    
                    endforeach;
                    wp_reset_postdata();
    
                endif; // ( $posts )
            ?>
            </td>
            <td>
                <a href="<?php the_sub_field('scheda_tecnica')?>" class="notifiche" data-tipo="Scheda Tecnica">Scarica la Scheda Tecnica</a>
            </td>
            <td>
                <a href="<?php the_sub_field('scheda_di_sicurezza')?>" class="notifiche" data-tipo="Scheda di Sicurezza">Scarica la Scheda di Sicurezza</a>
            </td>
        </tr>
    
        <?php endwhile; // has_sub_field( 'schede_prodotti' ) ?>
    </table>
    <?php endif; // get_field( 'schede_prodotti' ) ?>

    For better readability, I uploaded the code as a Gist.

    Please let me know if this solves your problem.