• Hi WordPress specialists,

    I’m sure that there are some of you who can help me here.

    I created the following filter for title and content of posts (for a jQuery live search):

    // additional filter to query "title like %...% or content like %...%"
    add_filter( 'posts_where', 'theme_title_content_like_posts_where', 10, 2 );
    function theme_title_content_like_posts_where( $where, &$wp_query ) {
        global $wpdb;
        if ( $post_title_content_like = $wp_query->get( 'post_title_content_like' ) ) {
            $where .= ' AND (' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_content_like ) ) . '%\' OR '. $wpdb->posts . '.post_content LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_content_like ) ) . '%\')';
        }
        return $where;
    }

    This works perfectly.

    But now the following question: Is it possible to extend the filter function that I created in the following way (written in a semantically understandable form)?

    […] OR custom field ‘author-name’ LIKE %searchterm% OR name of WP author (post_author) LIKE %searchterm%

    In other words: Is it possible – and if yes: how – to extend the ‘posts_where’ filter so that fields from other database tables can be included?

    Thanks in advance for your help!

    Best regards
    joschi81

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

    (@joschi81)

    Ok, mission 1 accomplished, here’s how you can extend the posts_where filter to search for a string within title, content and display name of user:

    // additional filter to query "title like %...% or content like %...%" or post_author (display_name) like %...%
    add_filter( 'posts_where', 'theme_title_content_like_posts_where', 10, 2 );
    function theme_title_content_like_posts_where( $where, &$wp_query ) {
      global $wpdb;
      if ( $post_title_content_like = $wp_query->get( 'post_title_content_like' ) ) {
        $where .= ' AND (' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_content_like ) ) . '%\'';
        $where .= ' OR '. $wpdb->posts . '.post_content LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_content_like ) ) . '%\'';
        $where .= ' OR '. $wpdb->posts . '.post_author IN (SELECT ID FROM '.$wpdb->users.' WHERE display_name  LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_content_like ) ) . '%\' ))';
      }
      return $where;
    }

    Now, going over to mission 2: Including my custom author-name field.

    Any hints?

    Best regards
    joschi81

Viewing 1 replies (of 1 total)

The topic ‘'posts_where' filer: complex condition including custom fields possible?’ is closed to new replies.