Skip to content

Add filter hooks for AJAX suggest results #604

@apermo

Description

@apermo

Problem

The "select translation" AJAX autocomplete (suggest_posts / suggest_terms) returns results with no way
to alter the final result set before it reaches the browser.

Existing filters operate upstream:

  • msls_meta_box_suggest_args / msls_post_tag_suggest_args — modify query args before fetching
  • msls_meta_box_suggest_post / msls_post_tag_suggest_term — modify individual items in the loop

There is no filter on the collected results array. This makes it impossible for add-on plugins to:

  • Re-sort results (e.g., put heuristically likely matches first)
  • Modify labels (e.g., add match-probability prefixes)
  • Insert spacers or group separators
  • Remove or reorder entries based on custom logic

Proposal

1. Two new filters on the final results

msls_meta_box_suggest_results (posts) and msls_post_tag_suggest_results (terms)

Applied after all items are collected and sorted, before JSON encoding. Each filter receives:

  • $resultsarray<int, array{value: int, label: string}>, alphabetically sorted by default
  • $context — associative array with blog_id, post_type (or taxonomy), s (search term), source_id

2. Pass source_id in the AJAX request

Currently the AJAX request does not include the ID of the post/term being edited. Without this, filter
consumers can't implement heuristic matching (e.g., "this post's title is similar to...").

Changes:

  • Add a hidden field #msls_source_id in the metabox HTML (posts: $post->ID, terms: $tag->term_id)
  • JS sends source_id in the AJAX POST data
  • New FIELD_SOURCE_ID constant in MslsFields

Example usage

add_filter('msls_meta_box_suggest_results', function (array $results, array $context): array {
    // Access the source post for comparison
    $source = get_post($context['source_id']);

    // Score and sort by title similarity
    usort($results, function ($a, $b) use ($source) {
        $score_a = similar_text($source->post_title, $a['label']);
        $score_b = similar_text($source->post_title, $b['label']);
        return $score_b - $score_a;
    });

    // Prefix top match
    if (!empty($results)) {
        $results[0]['label'] = '' . $results[0]['label'];
    }

    return $results;
}, 10, 2);

Files to modify

  • includes/MslsFields.php — add FIELD_SOURCE_ID constant + config
  • includes/MslsMetaBox.php — add hidden field in render_input(), add filter in suggest()
  • includes/MslsPostTag.php — add hidden field in add_input()/edit_input(), add filter in suggest()
  • src/msls.js — send source_id in AJAX request

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions