27.09.2022, Technical documentation & snippets

Fill Elementor posts widget with ACF relationship field

With the posts widget in Elementor, you can easily display other posts, pages, products or custom post types (CPT) (= user-defined content types) on a page in a loop. It only gets tricky if 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 does not offer Elementor.

Solution:

  1. ACF relationship 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 "Posts" widget to the desired location
  3. Elementor settings: Source: -> Content type
  4. Query ID: Enter an individual ID, e.g. "acf_relation
  5. All content types now appear in the preview, which we will now change.
  6. Save and exit Elementor Editor
  7. 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' );
} );

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

See also