Skip to content

Instantly share code, notes, and snippets.

@szepeviktor
Last active August 22, 2025 08:49
Show Gist options
  • Select an option

  • Save szepeviktor/43e06c132dcdcc55aadf971719da1c5a to your computer and use it in GitHub Desktop.

Select an option

Save szepeviktor/43e06c132dcdcc55aadf971719da1c5a to your computer and use it in GitHub Desktop.
WC Admin Search by Global Unique ID
<?php
/**
* Plugin Name: WC Admin Search by Global Unique ID
* Description: Make the admin Products search match the _global_unique_id (GTIN/EAN/UPC/ISBN).
* Version: 1.0.0
* WC requires at least: 9.2
* Requires PHP: 7.4
* Author: Viktor Szépe
* Author URI: https://www.szepe.net/
*/
if (!defined('ABSPATH')) { exit; }
add_filter('woocommerce_product_pre_search_products', function ($results, $term, $type, $include_variations, $all_statuses, $limit)
{
if (!is_admin() || !function_exists('get_current_screen')) {
return $results;
}
$screen = get_current_screen();
if (!$screen || $screen->id !== 'edit-product') {
return $results;
}
$term = trim((string)$term);
if ($term === '') {
return $results;
}
global $wpdb;
$post_statuses = current_user_can('edit_private_products') ? ['private', 'publish'] : ['publish'];
$post_types = $include_variations ? ['product', 'product_variation'] : ['product'];
$like = '%' . $wpdb->esc_like($term) . '%';
$limit_sql = $limit ? $wpdb->prepare('LIMIT %d', (int)$limit) : 'LIMIT 1000';
$types_in = implode("','", array_map('esc_sql', $post_types));
$status_in = implode("','", array_map('esc_sql', $post_statuses));
$sql = "
SELECT DISTINCT
CASE p.post_type WHEN 'product_variation' THEN p.post_parent ELSE p.ID END AS product_id
FROM {$wpdb->posts} p
INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID
WHERE p.post_type IN ('{$types_in}')
AND p.post_status IN ('{$status_in}')
AND pm.meta_key = %s
AND pm.meta_value LIKE %s
{$limit_sql}
";
$ids = $wpdb->get_col($wpdb->prepare($sql, '_global_unique_id', $like)); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
if (empty($ids)) {
return $results;
}
return array_values(array_unique(array_map('intval', $ids)));
}, 10, 6);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment