-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
46 lines (39 loc) · 1.31 KB
/
index.php
File metadata and controls
46 lines (39 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/*
* Plugin Name: WooCommerce Search by SKU
* Description: Enhance WooCommerce search to include SKU.
* Version: 1.0
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: P4UL
* Author URI: https://www.p4ul.dev
* License: DBAD
* License URI: https://dbad-license.org/
* Text Domain: woocommerce-search-by-sku
*/
if(!defined('ABSPATH')):
exit; // Exit if accessed directly.
endif;
function search_by_sku($search, $wp_query) {
global $wpdb;
if(is_admin() || !$wp_query->is_search() || !$wp_query->is_main_query()):
return $search;
endif;
// GET THE SEARCH QUERY
$search_query = $wp_query->get('s');
if(empty($search_query)):
return $search;
endif;
// CHECK IF WOOCOMMERCE IS ACTIVE
if(!class_exists('WooCommerce')):
return $search;
endif;
// MODIFY SEARCH TO INCLUDE SKU
$search = " AND (";
$search .= " {$wpdb->posts}.post_title LIKE '%".esc_sql($search_query)."%'";
$search .= " OR {$wpdb->posts}.post_content LIKE '%".esc_sql($search_query)."%'";
$search .= " OR EXISTS (SELECT * FROM {$wpdb->postmeta} WHERE {$wpdb->postmeta}.meta_key = '_sku' AND {$wpdb->postmeta}.meta_value LIKE '%".esc_sql($search_query)."%' AND {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID)";
$search .= ")";
return $search;
}
add_filter('posts_search', 'search_by_sku', 10, 2);