• My custom post type search works when I’m searching a keyword found in the posts. But when I search a keyword or term NOT found in any posts it displays some random post anyway, often the same posts. These custom post types are not simply blog pages, they are complex directory listings with many meta fields that I had to query in the search. Could someone direct me as to how I would find out why keywords that should result in “No posts found” result random post results?

    Please go to: http://northwestdharma.org/nw-dharma-news-wp/group-directory/ to see my issue. Thank you.

Viewing 1 replies (of 1 total)
  • Thread Starter SpicyNumberOne

    (@spicynumberone)

    If anyone who has seen this post and can pass it on to someone who knows PHP, SQL and WordPress search functions, I would be so grateful. At this point I will hire the person by the hour to fix this glitch, I just don’t know how to find and hire truly expert WordPress developers.

    Here is the code that is producing results correctly when the search term exists, and produces 6 results when the search term does not exist.

    <?php
          global $wpdb;
    
           $keyword = get_search_query();
           $keyword = '%' . like_escape( $keyword ) . '%';
    
          // Search in all custom fields
          $post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
              SELECT DISTINCT post_id FROM {$wpdb->postmeta}
              WHERE meta_value LIKE '%s'
          ", $keyword ) );
    
          // Search in post_title and post_content
          $post_ids_post = $wpdb->get_col( $wpdb->prepare( "
              SELECT DISTINCT ID FROM {$wpdb->posts}
              WHERE post_title LIKE '%s'
              OR post_content LIKE '%s'
          ", $keyword, $keyword ) );
          $post_ids = array_merge( $post_ids_meta, $post_ids_post );
    
          // Query arguments
          $args = array(
              'post_type'   => 'directory',
              'post_status' => 'publish',
              'post__in'    => $post_ids,
          );
    
          $query = new WP_Query( $args );
    
          if ( $query->have_posts() ): while ( $query->have_posts() ) : $query->the_post(); ?>

    To give more details about my problem, the meta is the root of the problem. Someone pointed out that they believe you should not merge the ids and the meta:

    $post_ids = array_merge( $post_ids_meta, $post_ids_post );

    Another suggestion to me was to use WP_Meta_Query to query the meta. But, all of my tries produced PHP errors because I am not fluent in PHP. This problem has become urgent, please help.

Viewing 1 replies (of 1 total)
  • The topic ‘Custom Post Type Search Results Showing A Positive Negatives’ is closed to new replies.