Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // miken32's approach
- function ma_post_title_filter($where, &$wp_query) {
- global $wpdb;
- $punct = ["’", "‘", "”", "“"];
- if ( $search_term = $wp_query->get( 'ma_search_post_title' ) ) {
- // escape any % or _ characters
- $search_term = $wpdb->esc_like($search_term);
- // replace desired punctuation characters with _
- $search_term = str_replace($punct, "_", $search_term);
- // do final escaping for safe queries
- $search_term = $wpdb->real_escape($search_term);
- // this looks much neater with string interpolation vs concatenation
- $where .= " AND $wpdb->posts.post_title LIKE '%$search_term%'";
- }
- return $where;
- }
- $args = array(
- 'ma_search_post_title' => $search_term, // search post title only
- 'suppress_filters' => FALSE, // this is required for the 'ma_post_title_filter' to work
- 'numberposts' => 5,
- 'post_type' => 'any',
- 'fields' => 'ids',
- 'ignore_sticky_posts' => true,
- 'no_found_rows' => true,
- );
- add_filter( 'posts_where', 'ma_post_title_filter', 10, 2 );
- $posts = get_posts($args);
- remove_filter( 'posts_where', 'ma_post_title_filter', 10 );
- print_r($posts);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement