Site logo

Archived topic

Display field of an ACF relationship of all posts in a Query Loop

3 replies · Started by Julien on January 9, 2023

Viewing posts 1–4 of 4

Hi,

I have Companies and Jobs ACF entities, with a relationship (a job has one company).

With Elements, I created a Block containing a Job Query Loop to display all jobs. However, for each job, I need to display also some of Company fields.

I read that arrays are not supported, so it may explain why I can do it successfully.

I've read this post but I am not sure it's the same use-case, as $relationships = get_post_meta(get_the_id(),'myrelationship',true); will return the page ID and not the job ID in the query loop.

Any idea how to implement that?

Many thanks

Hi there,

so when it comes to blocks and particularly those that create a loop, you can use the render_block filter to swap the content of a block with some other content.

1. Add a GB Block such as a Headline Block to your query loop.
1.1 Add some static text and NO dynamic data
1.2 In its Advanced > Additional CSS Class(es) add a custom class eg. your-custom-class
1.3 Note this class is used in the PHP snippet to target that block.

2. And here is an example of using the render_block filter to swap out that blocks content for you custom fields:

add_filter( 'render_block', function( $block_content, $block ) {
	
    // Set the conditions for render
    if (
        !is_admin() 
        && ! empty( $block['attrs']['className'] )
        && 'your-custom-class' === $block['attrs']['className'] // match class of your block
        ){
            // create a html variable
            $html = '';
            // get your custom field
            $relationships = get_field('relationship_field');
            // check the field has data 
            if( $relationships ) { 
                // loop through the field array
                foreach( $relationships as $relationship ) { 
                    // get the array itme fieldname 
                    $custom_field = get_field( 'field_name', $relationship->ID );
                }
                // print the custom field to the HTML
                $html .= '<span>' .  $custom_field . '</span>';
            }
            $block_content = $html;
    }
    
    return $block_content;

}, 10, 2 );

Update the className to match your CSS class on the block.
And update the code within the condition to output the fields you require.

Many thanks; it's a good workaround!

You're welcome

This archived topic is closed to new replies.