1

So I am using post object which allows me to search a custom post type by the title. What I want to do is search the custom post type by a custom field and have the custom field values returned. At the moment I have the following code in my functions.php file:-

function my_post_object_query( $args, $field, $post_id ) {

    // Get the search text
    $the_search = $args['s'];

    // Remove it so ACF won't search the posts based on title
    unset($args['s']);

    // Search based on custom field
    $args['meta_key'] = 'short_title';
    $args['meta_value'] =  $the_search;
    $args['meta_compare'] = 'LIKE';

    // return
    return $args;

}

// filter for a specific field based on it's name
add_filter('acf/fields/post_object/query/name=product', 'my_post_object_query', 10, 3);

This is allowing me to search using a custom field but the returned values are still the the_title(). How can I change the returned values to the same custom field; short_title

Thanks

2

There's another filter for the post_object: acf/fields/post_object/result, that lets you customise the result (text) displayed for each option in the post object field.

Try something like this:

function my_post_object_result( $title, $post, $field, $post_id ) {

    /* Get whatever value you want here e.g. */
    $short_title= get_field('short_title', $post->ID);

    /* do any other processing you might want to do before returning it... */ 

    return $short_title;
}

add_filter('acf/fields/post_object/result/name=product', 'my_post_object_result', 10, 4);

Reference: ACF Documentation for acf/fields/post_object/result

  • Perfect thank you! Although you've missed the $, so it's return $short_title; – nsilva Sep 27 '17 at 9:53
  • Oops! I'll fix that typo, just in case anyone else might find this answer useful :) – FluffyKitten Sep 27 '17 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.