Support

Account

Home Forums General Issues Repeater query through different posts : order results by subfield value

Solving

Repeater query through different posts : order results by subfield value

  • Hi,

    I have a custom post type (“Clients”) with a repeater (“Payments”) and 2 subfields : Date and Amount.

    I have a query that loops through all the posts “clients”, in each post loops through the repeater, and puts the payments in a table, 1 payment per row:

    Client 1 – 12/01/2022 – 50€
    Client 1 – 23/02/2022 – 170€
    Client 2 – 02/12/2021 – 1000€
    Client 2 – 07/03/2022 – 4000€
    Client 3 – 10/02/2022 – 100€

    I would like to order this table by date of payment?
    So as i get this result:

    Client 2 – 02/12/2021 – 1000€
    Client 1 – 12/01/2022 – 50€
    Client 3 – 10/02/2022 – 100€
    Client 1 – 23/02/2022 – 170€
    Client 2 – 07/03/2022 – 4000€

    I have seen some threads related to the issue (example), but couldn’t work it out myself.

    If necessary, here is my code (simplified a lot for the example, so a mistake might have slipped in)

    <table>

    <?php $args = array(
    ‘post_type’ => ‘clients’,
    ‘posts_per_page’ => ‘-1’,
    );

    $post_query = new WP_Query($args);

    if($post_query->have_posts() ) {
    while($post_query->have_posts() ) {
    $post_query->the_post();

    $payments = get_field(‘payments’);

    if( $payments ) {
    foreach( $payments as $payment ) {

    $date = $payment[‘date’];
    $amount = $payment[‘amount’];
    ?>

    <tr>
    <td><?php echo the_title(); ?></td>
    <td><?php echo $date; ?></td>
    <td><?php echo $amount; ?></td>
    </tr>

    <?php }}}} ?>
    </table>

    Thank you!

  • You cannot sort posts by a repeater sub field.

    But that is also not what you are trying to do, you want to sort the repeater for display. What you need to look at is this https://www.advancedcustomfields.com/resources/how-to-sorting-a-repeater-field/

  • Hi,

    Indeed i’m not trying to sort posts.

    I had seen the link you posted, but if I understand correctly this is used to sort a repeater in one post ? Like, if i’m in the post “John”, i can sort the payments of that client by date.

    Would this also allow me to get all the payments(repeater rows) from all the clients(posts) and sort them by date?
    If yes, then I’ll look more closely into it or ask my dev.

    Thank you !

  • The only way to get all of the repeaters form all of the client posts is to query the post and loop over them and perform the sorting on each post.

  • Hi John,
    So if i understand you correctly, what I want to do is not possible ?

  • Nevermind, I managed to sort my table with Jquery instead, which is just as fine.
    Thank you

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

You must be logged in to reply to this topic.