Last active
April 17, 2018 22:58
-
-
Save hwkdev/691b7e3abb58e405568915e122674966 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| add_filter('posts_where', 'hwk_wp_query_post_like', 10, 2); | |
| function hwk_wp_query_post_like($where = '', &$wp_query){ | |
| global $wpdb; | |
| if(!$post_like = $wp_query->get('post_like')) | |
| return $where; | |
| if(is_string($post_like)) | |
| return $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql($wpdb->esc_like($post_like)) . '%\''; | |
| if(!is_array($post_like)) | |
| return $where; | |
| if(!isset($post_like[0]) || (!is_string($post_like[0]) && !is_array($post_like[0]))) | |
| return $where; | |
| $post_like = wp_parse_args($post_like, array( | |
| 'relation' => 'OR', | |
| 'column' => 'post_title', | |
| )); | |
| $post_title_like_array = array(); | |
| $post_title_like_array[] = $post_like[0]; | |
| if(is_array($post_like[0])){ | |
| $post_title_like_array = array(); | |
| foreach($post_like[0] as $k => $rule){ | |
| $post_title_like_array[] = $rule; | |
| } | |
| } | |
| $where_addon = array(); | |
| foreach($post_title_like_array as $keyword){ | |
| $where_addon[] = $wpdb->posts . '.' . $post_like['column'] . ' LIKE \'%' . esc_sql($wpdb->esc_like($keyword)) . '%\''; | |
| } | |
| $where .= ' AND ( ' . implode(' ' . $post_like['relation'] . ' ', $where_addon) . ' )'; | |
| return $where; | |
| } | |
| /* | |
| // Usage: | |
| // Post_title like 'Contact' OR 'Informations': | |
| $query = new WP_Query(array( | |
| 'post_type' => 'page', | |
| 'posts_per_page' => -1, | |
| 'post_like' => array( | |
| 'relation' => 'OR', // OR | AND - default: OR | |
| 'column' => 'post_title', // post_title | post_content etc... - default: post_title | |
| array( | |
| 'Contact', | |
| 'Informations', | |
| ) | |
| ) | |
| )); | |
| // Post_title like 'Contact' AND 'Informations': | |
| $query = new WP_Query(array( | |
| 'post_type' => 'page', | |
| 'posts_per_page' => -1, | |
| 'post_like' => array( | |
| 'relation' => 'AND', | |
| array( | |
| 'Contact', | |
| 'Informations', | |
| ) | |
| ) | |
| )); | |
| // Post_title like 'Contact': | |
| $query = new WP_Query(array( | |
| 'post_type' => 'page', | |
| 'posts_per_page' => -1, | |
| 'post_like' => 'Contact' | |
| )); | |
| // Post_content like 'Contact': | |
| $query = new WP_Query(array( | |
| 'post_type' => 'page', | |
| 'posts_per_page' => -1, | |
| 'post_like' => array( | |
| 'column' => 'post_content', | |
| array( | |
| 'Contact' | |
| ) | |
| ) | |
| )); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment