Custom WordPress Rest Endpoint with custom query loop

add this code to your functions.php and edit it to your needs

on this example

I am getting results from “post” posttype and getting results for id, title, thumbnail, content, homepage named custom field and file-upload custom field

you can remove, add or edit to your needs this fields.

 

// https://yourwebsite.org/wp-json/custom/v1/field








add_action( 'rest_api_init', function () {
  register_rest_route( 'custom/v1', '/field/', array(
    'methods' => 'GET',
    'callback' => 'custom_query_callback'
    
  ) );
} );

function custom_query_callback( $request ) {
  $args = array(
    'post_type' => array('post'),
    'meta_query' => array(
      array(
        'key' => 'homepage',
        'value' => 'YES',
        'compare' => '=',
      ),
    ),
    'orderby' => 'date',
    'order' => 'DESC',
    'posts_per_page' => 50, // Retrieve all matching posts
  );

  $query = new WP_Query( $args );

  $posts = array();
  while ( $query->have_posts() ) {
    $query->the_post();
       
     $get_file_id = get_post_meta( get_the_ID(), 'file-upload' , true );
     $get_the_url = wp_get_attachment_url($get_file_id);
       
       
    $post = array(
      'id' => get_the_ID(),
      'title' => get_the_title(),
       'thumbnail' => get_the_post_thumbnail_url(get_the_ID(),'full'),
      'content' => get_the_content(),
      'homepage' => get_post_meta( get_the_ID(), 'homepage' , true ),
      'file-upload' => $get_the_url
    );
       
       
    array_push( $posts, $post );
  }

  return $posts;
}






 

Leave the first comment