Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. <?php
  2.  
  3. add_filter( 'posts_search', 'm_cars_search_vin' );
  4.  
  5. function m_cars_search_vin( $where ) {
  6. global $pagenow, $wpdb, $wp;
  7.  
  8. // check if we are on the right page & performing a search & for the right post type
  9. if ( 'edit.php' != $pagenow || ! is_search() || ! isset( $wp->query_vars['s'] ) || 'cars' != $wp->query_vars['post_type'] ) {
  10. return $where;
  11. }
  12.  
  13. // the meta key of the custom field we are looking for
  14. $meta_key = '_car_vin';
  15.  
  16. $search_ids = array();
  17. $terms = explode( ',', $wp->query_vars['s'] );
  18.  
  19.  
  20. foreach ( $terms as $term ) {
  21. if ( is_numeric( $term ) ) {
  22. $search_ids[] = $term;
  23. }
  24.  
  25. // Attempt to get a VIN
  26. $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 ) ) . '%' ) );
  27. $vin_to_id = array_merge( wp_list_pluck( $vin_to_id, 'ID' ), wp_list_pluck( $vin_to_id, 'post_parent' ) );
  28.  
  29. // include the ids of relevant posts in the results
  30. if ( sizeof( $vin_to_id ) > 0 ) {
  31. $search_ids = array_merge( $search_ids, $vin_to_id );
  32. }
  33. }
  34.  
  35. $search_ids = array_filter( array_unique( array_map( 'absint', $search_ids ) ) );
  36.  
  37. if ( sizeof( $search_ids ) > 0 ) {
  38. // if ids found, change the where clause
  39. $where = str_replace( 'AND (((', "AND ( ({$wpdb->posts}.ID IN (" . implode( ',', $search_ids ) . ")) OR ((", $where );
  40. }
  41.  
  42. return $where;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement