Home Forums Backend Issues (wp-admin) Search relationship on custom field Reply To: Search relationship on custom field

  • I’m looking to do something similar, but I’m focusing on the use case that the user will enter either a product name or a SKU. Name is the title field, so that will come back in results by default. If they enter a SKU, that’s an ACF field.

    So, what I’m doing is firing a query against the default $args array, and if it contains posts, I return that array as-is.

    If it doesn’t return any posts, then I overwrite $args with a new array that looks at my custom field, and also removes the ‘s’ argument to kill the default search functionality.

    It seems to be working pretty well given this use case. I tried to combine both conditions using post__in, but you still wind up with the situation where you have the ‘s’ param searching in title and content, and creating a default ‘AND’ relationship with the meta_query. Also, if the title/content search succeeds, it never looks at the SKU, but that’s not an issue in my case since the SKU value is somewhat human un-readable and would make for a pretty lousy product title.

    My code is below for reference:

    function my_related_query($args, $field, $post_id) {
    	if ($args['s'] == '') {
    		// nothing passed in, so just return $args as it stands and get out of here.
    		return $args;
    	// check for posts using $args
    	$result = new WP_Query($args);
    	if ($result->found_posts == 0) {
    		// no posts found for the query, so it might be a sku... take a look there?
    		$args['meta_query'] = array(
    				'key' => 'sku',
    				'value' => $args['s'],
    				'compare' => 'like'
    		$args['posts_per_page'] = -1;
    		$args['s'] = '';
    	return $args;
    add_filter('acf/fields/relationship/query/name=related', 'my_related_query', 10, 3);