• This function is working no longer, why?

    add_filter('posts_where', 'posts_where');
        function posts_where($where)
            {
    
                $s = $_GET['s'];
    
                if(!empty($s))
                {
                  if(is_numeric($s))
                  {
                     global $wpdb;
    
                    $where = str_replace('(' . $wpdb->posts . '.post_title LIKE', '(' . $wpdb->posts . '.ID = ' . $s . ') OR (' . $wpdb->posts . '.post_title LIKE', $where);
                  }
                  elseif(preg_match("/^(\d+)(,\s*\d+)*\$/", $s)) // string of post IDs
                  {
                    global $wpdb;
    
                    $where = str_replace('(' . $wpdb->posts . '.post_title LIKE', '(' . $wpdb->posts . '.ID in (' . $s . ')) OR (' . $wpdb->posts . '.post_title LIKE', $where);
                  }
                }
    
    
              return $where;
            }
    

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Sort of works for me. The only issue is in finding a post with the specified IDs within post content, excerpt, or title. But only when multiple IDs were specified, single ID search works for me. Is multiple IDs in content even a condition you need to address? If so, I don’t see how this ever worked properly.

    The issue with multiple IDs is a post with the IDs in content must also have its own ID in the search list. For ?s=1, 2, you have essentially (simplified for clarity, I hope)

    (ID in (1,2) OR content LIKE %1%)
     AND
    (ID in (1,2) OR content LIKE %2%)

    To find posts whose ID is not specified but is in content, I think you’d want

    (ID in (1,2)) OR (
       (content LIKE %1%) AND (content LIKE %2%)
    )

    Maybe you’d also want that AND to be OR, IDK.

    In other words, the clause is doing exactly as you ask, even if it’s not what you wanted ??

    If you are having other issues besides what I’ve observed, it would be due to other code influencing the query and not specifically your code.

    just use get_posts() to search by post id in your PHP code.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘search post by post ID’ is closed to new replies.