<?php

/**
 * Ajax para retornar os posts/pages
 */
function o2_get_query_link() {

  if (!is_admin()) wp_send_json_error(['message' => 'Acesso negado'], 400);

  $args = array(
    'post_type' => 'any',
    'posts_per_page' => -1,
    'order' => 'date',
    'orderby' => 'DESC',
    's' => $_POST['s']
  );

  $query = new WP_Query($args);
  $data = array();

  while ($query->have_posts()) {
    $query->the_post();

    $page = array(
      'ID' => get_the_ID(),
      'title' => get_the_title(),
      'url' => get_the_permalink(),
      'type' => get_post_type()
    );

    $data[] = $page;
  }

  wp_send_json_success($data, 200);
}
if (is_admin()) {
  add_action('wp_ajax_o2_get_query_link', 'o2_get_query_link');
  add_action('wp_ajax_nopriv_o2_get_query_link', 'o2_get_query_link');
}
