Elementor posts widget fill with ACF relationship field

Table of contents

With the posts widget in Elementor, you can easily display other posts, pages, products or custom post types (CPT) on a page in a loop. The only tricky part is when you want to display the content of a meta field, e.g. an ACF relationship field.

Problem:

The option offers ACF relationship in post widget Elementor does not offer.

Solution:

  1. ACF Relation field (e.g. field name "my_acf_relationship_field") on the desired page or content type and fill it with data.
  2. In Elementor, drag the "Contributions" widget to the desired location.
  3. Settings Elementor: Source: -> Content type
  4. Query ID: Enter an individual ID, e.g. "acf_relation
  5. In the preview, all content types now appear first, let's change that now.
  6. Save and exit Elementor Editor
  7. Edit functions.php (Note: Only work on the Child Theme!). The following code changes the WP_Query object of Elementor:
add_action( 'elementor/query/acf_relation', function ( WP_Query $query ) {
   $ids = get_field('my_acf_relationship_field', get_the_ID());
   $query->set( 'post__in', $ids );
   $query->set( 'orderby', 'post__in' );
} );

Now the correspondingly selected relationships should be displayed in the same order as they appear in the ACF relationship field.