Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

jsarnowski / jsarnowski/jet-engine   php

Repository URL to install this package:

Version: 2.7.7 

/ classes / posts-search.php

<?php
/**
 * Posts search handler class
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

class Jet_Engine_Posts_Search_Handler {

	public function __construct() {
		// Force search posts control to work
		add_action( 'wp_ajax_cx_search_posts', array( $this, 'process_posts_search' ) );
		add_action( 'wp_ajax_jet_engine_meta_box_posts', array( $this, 'process_posts_search' ) );
	}

	/**
	 * Process posts search
	 *
	 * @return void
	 */
	public function process_posts_search() {

		add_filter( 'posts_where', array( $this, 'force_search_by_title' ), 10, 2 );

		$type    = $_REQUEST['post_type'];
		$query   = isset( $_GET['q'] ) ? esc_attr( $_GET['q'] ) : '';
		$type    = explode( ',', $type );
		$exclude = ! empty( $_GET['exclude'] ) ? explode( ',', $_GET['exclude'] ) : false;

		$args = array(
			'post_type'           => $type,
			'ignore_sticky_posts' => true,
			'posts_per_page'      => -1,
			'suppress_filters'    => false,
			's_title'             => $query,
		);

		if ( in_array( 'attachment', $type ) ) {
			$args['post_status'] = array( 'publish', 'inherit' );
		}

		if ( $exclude ) {
			$args['post__not_in'] = $exclude;
		}

		$posts = get_posts( $args );

		remove_filter( 'posts_where', array( $this, 'force_search_by_title' ), 10, 2 );

		$result = array();

		if ( ! empty( $posts ) ) {
			foreach ( $posts as $post ) {
				$result[] = array(
					'id'   => $post->ID,
					'text' => $post->post_title,
				);
			}
		}

		wp_send_json( array(
			'results' => $result,
		) );

	}

	/**
	 * Force query to look in post title while searching
	 *
	 * @return [type] [description]
	 */
	public function force_search_by_title( $where, $query ) {

		$args = $query->query;

		if ( ! isset( $args['s_title'] ) ) {
			return $where;
		} else {
			global $wpdb;

			$searh = esc_sql( $wpdb->esc_like( $args['s_title'] ) );
			$where .= " AND {$wpdb->posts}.post_title LIKE '%$searh%'";

		}

		return $where;
	}

}