BP_Search_CPT::sql( $search_term,  $only_totalrow_count = false )

Description

Source

File: bp-search/plugins/search-cpt/class-bp-search-cpt.php

		public function sql( $search_term, $only_totalrow_count=false ){

			global $wpdb;

			$bp_prefix = bp_core_get_table_prefix();

			$query_placeholder = array();

			$sql = " SELECT ";

			if( $only_totalrow_count ){
				$sql .= " COUNT( DISTINCT id ) ";
			} else {
				$sql .= " DISTINCT id , %s as type, post_title LIKE '%%%s%%' AS relevance, post_date as entry_date  ";
				$query_placeholder[] = $this->search_type;
				$query_placeholder[] = $search_term;
			}

			$sql .= " FROM {$wpdb->prefix}posts p";

			$tax 			 = array();
			$taxonomies = get_object_taxonomies( $this->cpt_name );
			foreach ( $taxonomies as $taxonomy ) {
				if ( bp_is_search_post_type_taxonomy_enable( $taxonomy, $this->cpt_name ) ) {
					$tax[] = $taxonomy;
				}
			}

			//Tax query left join
			if ( ! empty( $tax ) ) {
				$sql .= " LEFT JOIN {$wpdb->term_relationships} r ON p.ID = r.object_id ";
			}

			$sql .= " WHERE 1=1 AND ( p.post_title LIKE %s OR {$bp_prefix}bp_strip_tags(p.post_content) LIKE %s ";
			$query_placeholder[] = '%'.$search_term.'%';
			$query_placeholder[] = '%'.$search_term.'%';

			//Tax query
			if ( ! empty( $tax ) ) {

				$tax_in_arr = array_map( function( $t_name ) {
					return "'" . $t_name . "'";
				}, $tax );

				$tax_in = implode( ', ', $tax_in_arr );

				$sql .= " OR  r.term_taxonomy_id IN (SELECT tt.term_taxonomy_id FROM {$wpdb->term_taxonomy} tt INNER JOIN {$wpdb->terms} t ON 
					  t.term_id = tt.term_id WHERE ( t.slug LIKE %s OR t.name LIKE %s ) AND  tt.taxonomy IN ({$tax_in}) )";
				$query_placeholder[] = '%'. $search_term .'%';
				$query_placeholder[] = '%'. $search_term .'%';
			}

			//Post should be publish
			$sql .= " ) AND p.post_type = %s AND p.post_status = 'publish'";
			$query_placeholder[] = $this->cpt_name;

			$sql = $wpdb->prepare( $sql, $query_placeholder );

            return apply_filters(
                'BP_Search_CPT_sql',
                $sql,
                array(
                    'post_type'             => $this->cpt_name,
                    'search_term'           => $search_term,
                    'only_totalrow_count'   => $only_totalrow_count,
                )
            );
		}

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.