Adjust ACF Related posts loop

I love how versatile Bricks is, but having some trouble. Trying to use sort related posts in a loop, but bricks gives very little control of this. Is there a way to help this situation?

1 Like

There isn’t enough detail to answer you. Is this the POSTS element, or your own query. What are you querying, and how do you want to sort it. What problem are you having?

This is using a standard DIV, with the query loop turned on. When the ACF relationship it only shows the name, with no adjustments possible to the posts it pulls.

maybe @aslotta can do this via an ACF native function like he did for ACF repeater sorting in this thread

So far I haven’t found any challenge that aslotta couldn’t overcome.

Cheers

Patric

I am open to all ideas. I originally thought I was doing something wrong, and it should give controls, but I have find no way to do so.

Hi there

I think I got it!

“Standard” ACF Relationship query in Bricks:

Sort3

Sort4

Output before activating my code snippet:

Output after activating my code snippet:

The found posts are sorted by title.

This is the code:

<?php 
function my_acf_format_value( $value, $post_id, $field ) {
   // sort the relationship field by the post titles
    if (!empty($value)){
     
        $title = array();
        $z = 0;
        foreach( $value as $item ) {
        $z = $z + 1;
        // for this example I retrieve the title of the post
        $title[$z] = get_the_title( $item->ID );
        }
        array_multisort($title, $value);
        return $value;
        }
}

// Apply to ACF field with the ACF id_key
 add_filter('acf/format_value/key=field_647d84d569bfd', 'my_acf_format_value', 10, 3);

I made this example that sorts the ACF relationship field field_647d84d569bfd by the post titles.

Cheers

Patric

Hi

now with Bricks v1.8, we can use the new bricks/query/result filter.

Put this into a code snippet or functions.php:

<?php 
add_filter( 'bricks/query/result', function( $result, $query_obj ){
  // Return: Element ID is not the right one
  if ( $query_obj->element_id !== 'hmhovo'  ) {
    return $result;
  }
        if (!empty($result)) {
        $title = array();
        $z = 0;
        foreach( $result as $item ) {
        $z = $z + 1;
        // for this example I retrieve the title of the post
        $title[$z] = get_the_title( $item->ID );
        }
        array_multisort($title, $result);
        }
  return $result;
}, 10, 2 );

Sort1

Replace the element ID hmhovo in the code with your element ID of the repeater or relationship query.

Cheers

Patric