Search code examples
wordpresssearchcustom-post-typeargs

Custom Post Type Search


I'm building a custom post type search by post title. I have a post type 'produto' and two posts with the title 'Produto 1' and 'Produto teste 2'. The problem is when I put just 'f' in the search input the result is both posts instead of none.

I'm trying using the arg bellow but not success.

 $arg = array(
  'post_type' => 'produto',
          'search_prod_title' => '%'.$_POST['_searchvalue'].'%',
          'post_status' => 'publish',
          'orderby'     => 'title',
          'order'       => 'ASC'
      );

Solution

  • 'search_prod_title' is not allowed in the WordPress query. You can use either search parameter of wp_query :

    $args = array("post_type" => "mytype", "s" => $title);
    $query = get_posts( $args );
    

    Or you can get posts based on title throught wpdb class:

    global $wpdb;
    $myposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $wpdb->esc_like( $title ) .'%') );