Why doesn't my WordPress media search return partial matches?

I’m trying to build a search feature for my WordPress media library. It’s almost working, but there’s a snag. The search only gives me exact matches instead of partial ones.

For example, I’ve got two pictures: one named sprint and another called sprinting. When I look for sprint, I only get the first one. Shouldn’t LIKE in SQL find both?

Here’s a snippet of my code:

$query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s", '%' . $wpdb->esc_like($search_term) . '%');

$results = $wpdb->get_col($query);

foreach ($results as $attachment_id) {
    $thumb = wp_get_attachment_image($attachment_id, 'thumbnail');
    echo "<div class='image-box'>$thumb</div>";
}

Am I missing something obvious here? How can I make it find similar matches too?

hmm, interesting issue! have u thought about using a custom taxonomy for media? might help, right? also, what’s ur php version? i wonder if upgrading could change LIKE query behavior. any chance u tried var_dump to see what u gets?

hey swiftcoder15, had similar issue. try using ‘%s%’ instead of ‘%’ . $wpdb->esc_like($search_term) . ‘%’ in ur prepare statement. that shud catch partial matches. also double check ur db collation, it can mess with LIKE searches sometimes. goodluck!