| 1 |
<?php |
| 2 |
|
| 3 |
namespace ABlocks\Ajax; |
| 4 |
|
| 5 |
use ABlocks\Helper; |
| 6 |
use ABlocks\Classes\Sanitizer; |
| 7 |
|
| 8 |
if ( ! defined( 'ABSPATH' ) ) { |
| 9 |
exit; |
| 10 |
} |
| 11 |
|
| 12 |
use ABlocks\Classes\AbstractAjaxHandler; |
| 13 |
use WP_Query; |
| 14 |
|
| 15 |
class SearchBlock extends AbstractAjaxHandler { |
| 16 |
public function __construct() { |
| 17 |
$this->actions = array( |
| 18 |
'search_block_ajax_action' => array( |
| 19 |
'callback' => array( $this, 'search_blocks_ajax_handler' ), |
| 20 |
'allow_visitor_action' => true, |
| 21 |
'fields' => array( |
| 22 |
'current_page_id' => 'integer', |
| 23 |
'searchQuery' => 'string', |
| 24 |
'source' => 'string', |
| 25 |
) |
| 26 |
), |
| 27 |
); |
| 28 |
} |
| 29 |
|
| 30 |
public function search_blocks_ajax_handler( $payload ) { |
| 31 |
$searchQuery = $payload['searchQuery']; |
| 32 |
$source = $payload['source']; |
| 33 |
$current_page_id = $payload['current_page_id']; |
| 34 |
|
| 35 |
$args = array( |
| 36 |
's' => $searchQuery, |
| 37 |
'posts_per_page' => -1, |
| 38 |
'post_type' => $source, |
| 39 |
'post__not_in' => array( $current_page_id ), |
| 40 |
'post_status' => 'publish' |
| 41 |
); |
| 42 |
|
| 43 |
$query = new WP_Query( $args ); |
| 44 |
|
| 45 |
if ( $query->have_posts() ) { |
| 46 |
$results = array(); |
| 47 |
$results_html = ''; |
| 48 |
while ( $query->have_posts() ) { |
| 49 |
|
| 50 |
$query->the_post(); |
| 51 |
$title = get_the_title(); |
| 52 |
$link = get_permalink(); |
| 53 |
$thumbnail = get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' ); |
| 54 |
|
| 55 |
ob_start(); |
| 56 |
Helper::get_template('search-block/search-results.php', array( |
| 57 |
'title' => $title, |
| 58 |
'link' => $link, |
| 59 |
'thumbnail' => $thumbnail, |
| 60 |
)); |
| 61 |
$results_html .= ob_get_clean(); |
| 62 |
|
| 63 |
$results[] = array( |
| 64 |
'title' => get_the_title(), |
| 65 |
'link' => get_permalink(), |
| 66 |
'thumbnail' => get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' ), |
| 67 |
); |
| 68 |
}//end while |
| 69 |
|
| 70 |
wp_send_json_success(array( |
| 71 |
'html' => $results_html, |
| 72 |
'data' => $results |
| 73 |
)); |
| 74 |
}//end if |
| 75 |
|
| 76 |
} |
| 77 |
} |
| 78 |
|