TechEarl

Why ACF Relationship Fields Lose Their Selected Order

ACF Relationship fields keep the editor's order in the stored array but lose it in WP_Query. The fix is post__in plus orderby=post__in. Also: filtering the picker by post type, and a complete curated related-posts template with a fallback.

Ishan KarunaratnePublished ⏱️ 10 min readUpdated
Share thisCopied
ACF Relationship fields lose their order in WP_Query; fix it with orderby=post__in. Plus filtering the picker by post type and a related posts template.

ACF Relationship fields keep the editor's drag-and-drop order in the stored array, and get_field() returns it intact. The order is lost when you pass the IDs to WP_Query, because the default order is post_date DESC and post__in does not override it. Add 'orderby' => 'post__in' to every such query. This page also covers filtering the Relationship picker by post type (and taxonomy, meta, author) and a complete editor-curated related posts template built on the field.

Jump to:

What ACF actually returns

The ACF Relationship field has a "Return Format" setting with two options:

  • Post Object (default): returns an array of WP_Post objects in the editor's order.
  • Post ID: returns an array of integer IDs in the editor's order.

Both preserve order. The stored database value is an array of integer IDs, and get_field either returns them directly (ID format) or hydrates each one into a WP_Post (Object format), both in array order.

php
$related = get_field( 'related_posts', $post_id );
// With Post ID format:    [42, 7, 99, 13]
// With Post Object format: [WP_Post(42), WP_Post(7), WP_Post(99), WP_Post(13)]

That order is what the editor dragged in the field. ACF respects it.

Why WP_Query loses the order

The trouble starts when you take those IDs and pass them to WP_Query:

php
$ids = get_field( 'related_posts' );
$query = new WP_Query( [
    'post_type' => 'post',
    'post__in' => $ids,
] );
// Query returns posts in DEFAULT order (post_date DESC), not in $ids order

post__in filters which posts the query returns; it does not order them. The default orderby for WP_Query is post_date DESC. So the editor's order is silently lost as soon as the IDs enter the query.

This is by design (consistent with post__in's SQL semantics) but it is the cause of approximately 80% of "my Relationship field is showing the wrong order" tickets I have ever debugged.

The fix: orderby=post__in

The fix is one argument:

php
$ids = get_field( 'related_posts' );
$query = new WP_Query( [
    'post_type' => 'post',
    'post__in' => $ids,
    'orderby' => 'post__in', // <-- this
    'posts_per_page' => -1,
] );

orderby => 'post__in' tells WP_Query to return posts in the same order as the post__in array. ACF's stored order is preserved end-to-end. This single argument is the answer to almost every "Relationship field lost order" question.

Watch the gotcha: if you ALSO pass other ordering arguments ('orderby' => ['menu_order', 'post__in'] or similar combined forms), the post__in ordering may interact in unexpected ways. Default to the simple form unless you have a specific reason.

Pattern 1: looping over the array directly

When the rendered output is simple (a card per related post), the cleanest pattern skips WP_Query entirely and loops over the array ACF returned:

php
$related = get_field( 'related_posts' ); // Post Object format
if ( $related ) {
    foreach ( $related as $post ) {
        setup_postdata( $post );
        ?>
        <article class="card">
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <p><?php the_excerpt(); ?></p>
        </article>
        <?php
    }
    wp_reset_postdata();
}

This always preserves order because you are iterating the array directly. No WP_Query, no orderby concern.

The setup_postdata call lets you use the standard template tags (the_permalink, the_title, the_excerpt) as if you were inside the main loop. wp_reset_postdata restores the original $post global when you are done.

Pattern 2: passing IDs to WP_Query

When you need WP_Query's filtering features (tax_query, meta_query, status filtering), pass the IDs in and use orderby=post__in:

php
$ids = get_field( 'related_posts' ); // can be ID or Object format; this normalizes
if ( is_array( $ids ) && ! empty( $ids ) ) {
    $ids = array_map( fn( $p ) => is_object( $p ) ? $p->ID : (int) $p, $ids );
}

$query = new WP_Query( [
    'post_type' => 'post',
    'post__in' => $ids,
    'orderby' => 'post__in',
    'posts_per_page' => -1,
    'post_status' => 'publish', // useful if Relationship was set when posts were drafts
] );

while ( $query->have_posts() ) {
    $query->the_post();
    // ...
}
wp_reset_postdata();

This pattern is right when you want to filter the related posts (e.g., "only show published ones," "only ones in a specific category"). The order from the field is preserved.

Pattern 3: using setup_postdata in the_loop

When the related posts are displayed inside the main loop of a different post, the setup/reset pattern matters because the existing $post global needs to be restored:

php
the_post(); // main loop

// Inside the loop, render related posts
$related = get_field( 'related_posts' );
if ( $related ) {
    global $post; // save the outer post
    $outer_post = $post;

    foreach ( $related as $post ) {
        setup_postdata( $post );
        get_template_part( 'template-parts/related-card' );
    }

    $post = $outer_post;
    setup_postdata( $post ); // restore the outer post for the rest of the main loop
}

The manual $post save/restore matters because setup_postdata mutates the global. Without restoring it, the rest of your main-loop template code reads the LAST related post instead of the actual current post.

wp_reset_postdata reads from $wp_query->post to restore the global, which is fine when the related rendering is OUTSIDE the main loop, but inside the main loop it resets to "the current main-loop post" which may not be what you want if you have already advanced past it.

When ACF returns objects vs IDs

The Return Format setting controls what get_field gives you back. The data stored in the database is always an array of integer IDs; the format just controls hydration on read.

  • Post Object format: ACF runs get_post( $id ) for each ID and returns the array of WP_Post objects. Simpler to use in templates, slightly more meta read overhead per page.
  • Post ID format: returns the raw IDs. You hydrate yourself if you need the posts. Cheaper when you only want the IDs (for a WP_Query) or when you do not need the post objects at all.

For most agency templates, Post Object is the right default; the simplicity wins. For high-scale code paths (thousands of related-posts lookups), Post ID is faster.

To change the Return Format on an existing field: switch the setting in the field group editor. The stored data (the integer ID array) does not change. Templates need to be updated to handle the new shape. See How to Update ACF Fields Programmatically for the related write-side patterns.

The related posts template below uses Post ID format for exactly that reason: the IDs go straight into a WP_Query.

Filter the Relationship picker by post type

With its filters left empty, the Relationship picker lists posts of every post type and, per ACF's docs, of every status (drafts included), not just published ones. Two tools narrow it: the static settings in the field group editor, and the acf/fields/relationship/query filter for anything dynamic.

The static post type filter

Edit the Relationship field in the field group editor, find "Filter by Post Type", select the post types to include and save. Multiple post types are allowed (one field that links to both service and case_study posts, for example). The same screen has "Filter by Taxonomy" and "Filter by Post Status"; select Published there if editors should only link live content. If a static filter covers your case, stop there.

Dynamic filtering with acf/fields/relationship/query

acf/fields/relationship/query runs every time the picker queries posts. It receives the WP_Query arguments, the field config and the current post ID, and returns modified arguments:

php
add_filter( 'acf/fields/relationship/query', function ( $args, $field, $post_id ) {
    // Only apply this filter to a specific field by key or name
    if ( $field['name'] !== 'related_services' ) {
        return $args;
    }

    $args['post_status'] = 'publish';

    return $args;
}, 10, 3 );

The $field['name'] (or $field['key']) check matters: without it the filter applies to every Relationship field on the site. Every example below uses the same wrapper; only the body changes.

Only posts in a taxonomy term (here, the "featured" category):

php
$args['tax_query'] = [
    [
        'taxonomy' => 'category',
        'field' => 'slug',
        'terms' => 'featured',
    ],
];

Only posts where an ACF field matches (a True/False is_active field):

php
$args['meta_query'] = [
    [
        'key' => 'is_active',
        'value' => '1',
    ],
];

ACF True/False fields store 1 for true and 0 (or an empty string on older ACF versions) for false, so on older sites you may need a more permissive compare.

Exclude the current post from its own picker, so a "Related posts" field cannot reference itself:

php
if ( $post_id ) {
    $args['post__not_in'] = [ (int) $post_id ];
}

Only the current editor's own posts, unless they can edit others' posts (useful on multi-author sites):

php
if ( ! current_user_can( 'edit_others_posts' ) ) {
    $args['author'] = wp_get_current_user()->ID;
}

Sort the picker. It defaults to post_date DESC. For alphabetical order set $args['orderby'] = 'title' and $args['order'] = 'ASC'. For a custom priority field:

php
$args['meta_key'] = 'priority';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';

The picker order only affects what the editor sees while choosing. The saved order is still whatever the editor drags, and the front end still needs orderby=post__in.

Keep the picker fast

The filter runs every time the editor opens the picker, including paginated scrolling, so heavy queries make the editor feel slow. posts_per_page defaults to 20 in the picker; do not raise it without a reason. Avoid complex meta_query with many ANDs and ORs: if the condition is "ACF field X matches Y", mirror it into a custom taxonomy with the pattern in Useful Things You Can Do with acf/save_post and filter by taxonomy, which is much faster. On directory sites with hundreds of thousands of posts the picker can be slow regardless; a Post Object field with autocomplete or a custom picker is the better choice there.

An editor-curated related posts system on a Relationship field is three pieces: a field group with one Relationship field, a render partial that loops the curated picks, and an algorithmic fallback for posts where the editor has not picked any. It is around 80 lines of code and handles the standard cases I have shipped on agency content sites for years.

The field group

php
add_action( 'acf/init', function () {
    if ( ! function_exists( 'acf_add_local_field_group' ) ) return;

    acf_add_local_field_group( [
        'key' => 'group_related_posts',
        'title' => 'Related Posts',
        'fields' => [
            [
                'key' => 'field_related_posts',
                'name' => 'related_posts',
                'label' => 'Hand-picked related posts',
                'type' => 'relationship',
                'post_type' => ['post'],
                'filters' => ['search', 'post_type', 'taxonomy'],
                'return_format' => 'id',
                'min' => 0,
                'max' => 4,
                'instructions' => 'Optional. Leave empty to auto-select by category.',
            ],
        ],
        'location' => [
            [
                [
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ],
            ],
        ],
    ] );
} );

'min' => 0 lets editors leave it empty so the fallback runs, 'max' => 4 keeps the list reasonable, and 'return_format' => 'id' gives integer IDs to pass to WP_Query directly.

The render partial

php
<?php
// template-parts/related-posts.php
$curated_ids = get_field( 'related_posts' );
$related_ids = is_array( $curated_ids ) ? $curated_ids : [];

// Fallback to algorithmic related if no curated picks
if ( empty( $related_ids ) ) {
    $related_ids = te_algorithmic_related_ids( get_the_ID(), 4 );
}

// Belt and braces: never list the current post
$related_ids = array_diff( $related_ids, [ get_the_ID() ] );

if ( empty( $related_ids ) ) return;

$query = new WP_Query( [
    'post_type' => 'post',
    'post__in' => $related_ids,
    'orderby' => 'post__in',
    'posts_per_page' => count( $related_ids ),
    'post_status' => 'publish',
    'no_found_rows' => true,
    'update_post_meta_cache' => false,
] );

if ( ! $query->have_posts() ) return;
?>

<aside class="related-posts mt-16 border-t border-slate-200 pt-12">
    <h2 class="text-2xl font-bold mb-8">You might also like</h2>
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <article class="card group">
                <?php if ( has_post_thumbnail() ) : ?>
                    <a href="<?php the_permalink(); ?>" class="block aspect-video overflow-hidden rounded-lg">
                        <?php the_post_thumbnail( 'medium', [
                            'class' => 'w-full h-full object-cover group-hover:scale-105 transition',
                            'loading' => 'lazy',
                        ] ); ?>
                    </a>
                <?php endif; ?>
                <h3 class="mt-3 text-lg font-semibold leading-snug">
                    <a href="<?php the_permalink(); ?>" class="hover:underline">
                        <?php the_title(); ?>
                    </a>
                </h3>
                <p class="mt-2 text-sm text-slate-600">
                    <?php echo esc_html( wp_trim_words( get_the_excerpt(), 18 ) ); ?>
                </p>
            </article>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>
</aside>

'orderby' => 'post__in' is the fix from above that keeps the editor's order. 'no_found_rows' => true skips the SQL_CALC_FOUND_ROWS overhead because there is no pagination, and 'update_post_meta_cache' => false skips a meta pre-fetch the partial does not need (it only uses title, permalink, excerpt and thumbnail). The array_diff line guards posts whose Relationship data was saved before the exclude-current-post picker filter was in place.

The algorithmic fallback

The simplest fallback uses shared categories:

php
function te_algorithmic_related_ids( int $post_id, int $limit = 4 ): array {
    $categories = wp_get_post_categories( $post_id );
    if ( empty( $categories ) ) return [];

    $query = new WP_Query( [
        'post_type' => 'post',
        'posts_per_page' => $limit,
        'post__not_in' => [ $post_id ],
        'category__in' => $categories,
        'orderby' => 'date',
        'order' => 'DESC',
        'fields' => 'ids',
        'no_found_rows' => true,
        'update_post_meta_cache' => false,
    ] );

    return $query->posts;
}

It returns the latest four posts in the same categories, excluding the current one. Predictable and fast. Richer variants I have shipped combine category and tag overlap with weighted scoring, use custom taxonomy term overlap on directory sites, or fall through to "latest posts in any category" when the category match returns too few. On sites with a search backend the fallback queries that index instead; How to Add Semantic Search to a MySQL App covers that approach.

Fill empty slots after the curated picks

To use curated picks first and top up from the fallback so there are always four cards:

php
$curated_ids = get_field( 'related_posts' ) ?: [];
$total_wanted = 4;
$remaining = $total_wanted - count( $curated_ids );

$related_ids = $curated_ids;
if ( $remaining > 0 ) {
    $fallback_ids = te_algorithmic_related_ids( get_the_ID(), $remaining + count( $curated_ids ) );
    $fallback_ids = array_diff( $fallback_ids, $curated_ids ); // exclude already-curated
    $related_ids = array_merge( $related_ids, array_slice( $fallback_ids, 0, $remaining ) );
}

Cache the rendered block

On sites with traffic the block is a good candidate for fragment caching:

php
$cache_key = 'related_html_' . get_the_ID() . '_' . get_post_modified_time( 'U' );
$html = wp_cache_get( $cache_key, 'related-posts' );

if ( $html === false ) {
    ob_start();
    get_template_part( 'template-parts/related-posts' );
    $html = ob_get_clean();
    wp_cache_set( $cache_key, $html, 'related-posts', HOUR_IN_SECONDS );
}

echo $html;

The key includes the post's modified time, so when the editor updates the post (and re-curates), the cache invalidates on its own. For the broader case for ACF-driven curated content on agency builds, see Why Many Agencies Still Prefer ACF Over Gutenberg.

Sources

Authoritative references this article was fact-checked against.

TagsWordPressACFRelationship FieldWP_QueryFiltersRelated Posts

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Fill in your hash file, wordlist, mode and mask, then copy ready-to-run hashcat commands for every attack mode. Full flag reference, charset table, common modes. Tested on hashcat 7.1.2.

Hashcat Cheat Sheet: Build the Command, Copy, Crack

Set your hash file, wordlist, hash mode, and mask once at the top, and every command below fills in with your values, ready to copy and run. Then the full flag reference grouped by task, the mask charset table, and the common -m modes. Tested on hashcat 7.1.2.