| 1 |
<?php |
| 2 |
/** |
| 3 |
* REST API for grids. |
| 4 |
* |
| 5 |
* @link https://bootstrapped.ventures |
| 6 |
* @since 3.0.0 |
| 7 |
* |
| 8 |
* @package WP_Ultimate_Post_Grid |
| 9 |
* @subpackage WP_Ultimate_Post_Grid/includes/public/api |
| 10 |
*/ |
| 11 |
|
| 12 |
/** |
| 13 |
* REST API for grids. |
| 14 |
* |
| 15 |
* @since 3.0.0 |
| 16 |
* @package WP_Ultimate_Post_Grid |
| 17 |
* @subpackage WP_Ultimate_Post_Grid/includes/public/api |
| 18 |
* @author Brecht Vandersmissen <brecht@bootstrapped.ventures> |
| 19 |
*/ |
| 20 |
class WPUPG_API_Grids { |
| 21 |
|
| 22 |
/** |
| 23 |
* Register actions and filters. |
| 24 |
* |
| 25 |
* @since 3.0.0 |
| 26 |
*/ |
| 27 |
public static function init() { |
| 28 |
add_action( 'rest_api_init', array( __CLASS__, 'api_register_data' ) ); |
| 29 |
add_action( 'rest_insert_' . WPUPG_POST_TYPE, array( __CLASS__, 'api_insert_update_grid' ), 10, 3 ); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Register data for the REST API. |
| 34 |
* |
| 35 |
* @since 3.0.0 |
| 36 |
*/ |
| 37 |
public static function api_register_data() { |
| 38 |
if ( function_exists( 'register_rest_field' ) ) { |
| 39 |
register_rest_field( WPUPG_POST_TYPE, 'grid', array( |
| 40 |
'get_callback' => array( __CLASS__, 'api_get_grid_data' ), |
| 41 |
'update_callback' => null, |
| 42 |
'schema' => null, |
| 43 |
)); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Handle get calls to the REST API. |
| 49 |
* |
| 50 |
* @since 3.0.0 |
| 51 |
* @param array $object Details of current post. |
| 52 |
* @param mixed $field_name Name of field. |
| 53 |
* @param WP_REST_Request $request Current request. |
| 54 |
*/ |
| 55 |
public static function api_get_grid_data( $object, $field_name, $request ) { |
| 56 |
$grid = WPUPG_Grid_Manager::get_grid( $object['id'] ); |
| 57 |
return $grid ? $grid->get_data() : false; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Handle grid calls to the REST API. |
| 62 |
* |
| 63 |
* @since 3.0.0 |
| 64 |
* @param WP_Post $post Inserted or updated post object. |
| 65 |
* @param WP_REST_Request $request Request object. |
| 66 |
* @param bool $creating True when creating a post, false when updating. |
| 67 |
*/ |
| 68 |
public static function api_insert_update_grid( $post, $request, $creating ) { |
| 69 |
$params = $request->get_params(); |
| 70 |
$grid = isset( $params['grid'] ) ? WPUPG_Grid_Sanitizer::sanitize( $params['grid'] ) : array(); |
| 71 |
$grid_id = $post->ID; |
| 72 |
|
| 73 |
WPUPG_Grid_Saver::update_grid( $grid_id, $grid ); |
| 74 |
|
| 75 |
$grid = WPUPG_Grid_Manager::get_grid( $grid_id ); |
| 76 |
return $grid ? $grid->get_data() : false; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
WPUPG_API_Grids::init(); |
| 81 |
|