| 1 |
<?php |
| 2 |
|
| 3 |
namespace StoreEngine\Ajax; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; |
| 7 |
} |
| 8 |
|
| 9 |
use StoreEngine\Classes\AbstractAjaxHandler; |
| 10 |
|
| 11 |
class Posts extends AbstractAjaxHandler { |
| 12 |
public function __construct() { |
| 13 |
$this->actions = [ |
| 14 |
'fetch_posts' => [ |
| 15 |
'capability' => 'manage_options', |
| 16 |
'callback' => [ $this, 'fetch_posts' ], |
| 17 |
'fields' => [ |
| 18 |
'postType' => 'string', |
| 19 |
'postId' => 'id', |
| 20 |
'keyword' => 'string', |
| 21 |
], |
| 22 |
], |
| 23 |
]; |
| 24 |
} |
| 25 |
|
| 26 |
protected function fetch_posts( $payload ) { |
| 27 |
$post_type = ! empty( $payload['postType'] ) ? $payload['postType'] : 'page'; |
| 28 |
$postId = ! empty( $payload['postId'] ) ? $payload['postId'] : 0; |
| 29 |
$keyword = ! empty( $payload['keyword'] ) ? $payload['keyword'] : ''; |
| 30 |
|
| 31 |
if ( $postId ) { |
| 32 |
$args = [ |
| 33 |
'post_type' => $post_type, |
| 34 |
'p' => $postId, |
| 35 |
]; |
| 36 |
} else { |
| 37 |
$args = [ |
| 38 |
'post_type' => $post_type, |
| 39 |
'posts_per_page' => 10, |
| 40 |
]; |
| 41 |
if ( ! empty( $keyword ) ) { |
| 42 |
$args['s'] = $keyword; |
| 43 |
} |
| 44 |
if ( ! current_user_can( 'manage_options' ) ) { |
| 45 |
$args['author'] = get_current_user_id(); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
$results = []; |
| 50 |
$posts = get_posts( $args ); |
| 51 |
|
| 52 |
if ( is_array( $posts ) ) { |
| 53 |
foreach ( $posts as $post ) { |
| 54 |
$results[] = [ |
| 55 |
'value' => (int) esc_attr( $post->ID ), |
| 56 |
'label' => esc_html( $post->post_title ), |
| 57 |
]; |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
wp_send_json_success( $results ); |
| 62 |
} |
| 63 |
} |
| 64 |
|