How To Search by SKU In WordPress – ACF Query

In this tutorial I will show you what code you have to implement in your functions.php in order to make Post Object acf field search by a SKU. In this example we will use sku for a post object type product. Anyway using the same code you can add any type of custom query you need. 

Search by SKU

First step is to create our filed. So go to Custom Fields and create a new group. In this group create a Post Object field and select Product as your Post Type. Then, in your functions.php file you have to add the following code:

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/post_object/query/key=field_5dcd2e225bcd3', 'my_related_query', 10, 3);

As you can see we add a filter to acf/fields/post_object, in our example we add our new query only if there is no post found for your first query, but you can edit the code to meet your needs. It's nice because you can add any query you want here.

Let me know if you have any questions in comments section. 

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x