Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. <?php
  2.  
  3. // miken32's approach
  4. function ma_post_title_filter($where, &$wp_query) {
  5.     global $wpdb;
  6.     $punct = ["’", "‘", "”", "“"];
  7.     if ( $search_term = $wp_query->get( 'ma_search_post_title' ) ) {
  8.         // escape any % or _ characters
  9.         $search_term = $wpdb->esc_like($search_term);
  10.         // replace desired punctuation characters with _
  11.         $search_term = str_replace($punct, "_", $search_term);
  12.         // do final escaping for safe queries
  13.         $search_term = $wpdb->real_escape($search_term);
  14.         // this looks much neater with string interpolation vs concatenation
  15.         $where .= " AND $wpdb->posts.post_title LIKE '%$search_term%'";
  16.     }
  17.     return $where;
  18. }
  19.  
  20. $args = array(
  21.     'ma_search_post_title' => $search_term, // search post title only
  22.     'suppress_filters' => FALSE, // this is required for the 'ma_post_title_filter' to work
  23.     'numberposts' => 5,
  24.     'post_type' => 'any',
  25.  
  26.     'fields' => 'ids',
  27.     'ignore_sticky_posts' => true,
  28.     'no_found_rows' => true,
  29. );
  30.  
  31. add_filter( 'posts_where', 'ma_post_title_filter', 10, 2 );
  32. $posts = get_posts($args);
  33. remove_filter( 'posts_where', 'ma_post_title_filter', 10 );
  34.  
  35. print_r($posts);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement