Skip to content

Instantly share code, notes, and snippets.

@mircian
Created March 30, 2017 06:46
Show Gist options
  • Save mircian/36ca06f92c131bd3d4c2d72574ab65a8 to your computer and use it in GitHub Desktop.
Save mircian/36ca06f92c131bd3d4c2d72574ab65a8 to your computer and use it in GitHub Desktop.
<?php
add_filter( 'posts_search', 'm_cars_search_vin' );
function m_cars_search_vin( $where ) {
global $pagenow, $wpdb, $wp;
// check if we are on the right page & performing a search & for the right post type
if ( 'edit.php' != $pagenow || ! is_search() || ! isset( $wp->query_vars['s'] ) || 'cars' != $wp->query_vars['post_type'] ) {
return $where;
}
// the meta key of the custom field we are looking for
$meta_key = '_car_vin';
$search_ids = array();
$terms = explode( ',', $wp->query_vars['s'] );
foreach ( $terms as $term ) {
if ( is_numeric( $term ) ) {
$search_ids[] = $term;
}
// Attempt to get a VIN
$vin_to_id = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_parent FROM {$wpdb->posts} LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id WHERE meta_key='{$meta_key}' AND meta_value LIKE %s;", '%' . $wpdb->esc_like( wc_clean( $term ) ) . '%' ) );
$vin_to_id = array_merge( wp_list_pluck( $vin_to_id, 'ID' ), wp_list_pluck( $vin_to_id, 'post_parent' ) );
// include the ids of relevant posts in the results
if ( sizeof( $vin_to_id ) > 0 ) {
$search_ids = array_merge( $search_ids, $vin_to_id );
}
}
$search_ids = array_filter( array_unique( array_map( 'absint', $search_ids ) ) );
if ( sizeof( $search_ids ) > 0 ) {
// if ids found, change the where clause
$where = str_replace( 'AND (((', "AND ( ({$wpdb->posts}.ID IN (" . implode( ',', $search_ids ) . ")) OR ((", $where );
}
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment