SHARE
TWEET

WordPress get_post_with_title_like

qlstudio Jun 25th, 2014 241 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Get post with title %like% search term
  3.  *
  4.  * @param       $title          Post title to search for
  5.  * @param       $method         wpdb method to use to retrieve results
  6.  * @param       $columns        Array of column rows to retrieve
  7.  *
  8.  * @since       0.3
  9.  * @return      Mixed           Array || False
  10.  */
  11. function get_post_with_title_like( $title = null, $method = 'get_col', $columns = array ( 'ID' ) )
  12. {
  13.    
  14.     // sanity check ##
  15.     if ( ! $title ) { return false; }
  16.    
  17.     // global $wpdb ##
  18.     global $wpdb;
  19.    
  20.     // First escape the $columns, since we don't use it with $wpdb->prepare() ##
  21.     $columns = esc_sql( $columns );
  22.    
  23.     // now implode the values, if it's an array ##
  24.     if( is_array( $columns ) ){
  25.         $columns = implode( ', ', $columns ); // e.g. "ID, post_title" ##
  26.     }
  27.    
  28.     // run query ##
  29.     $results = $wpdb->$method (
  30.             $wpdb->prepare (
  31.             "
  32.                SELECT $columns
  33.                FROM $wpdb->posts
  34.                WHERE {$wpdb->posts}.post_title LIKE %s
  35.            "
  36.             ,   esc_sql( '%'.like_escape( trim( $title ) ).'%' )
  37.             )
  38.         );
  39.    
  40.     var_dump( $results );
  41.                
  42.     // return results or false ##
  43.     return $results ? $results : false ;
  44.    
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top