|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Test fields for MediaEdit component development. |
| 4 | + * |
| 5 | + * @package gutenberg |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * Register test media REST fields for MediaEdit component development. |
| 10 | + * |
| 11 | + * Creates 3 test fields: |
| 12 | + * - test_media_gallery: array type for multiple+expanded testing |
| 13 | + * - test_media_gallery_2: array type for multiple+compact testing |
| 14 | + * - test_media_single: integer type for single+expanded testing |
| 15 | + */ |
| 16 | +function gutenberg_register_media_edit_test_rest_fields() { |
| 17 | + $post_types = get_post_types( array( 'show_in_rest' => true ) ); |
| 18 | + |
| 19 | + // Define test fields: name => is_array. |
| 20 | + $fields = array( |
| 21 | + 'test_media_gallery' => true, // array - multiple+expanded. |
| 22 | + 'test_media_gallery_2' => true, // array - multiple+compact. |
| 23 | + 'test_media_single' => false, // integer - single+expanded. |
| 24 | + ); |
| 25 | + |
| 26 | + foreach ( $post_types as $post_type ) { |
| 27 | + foreach ( $fields as $field_name => $is_array ) { |
| 28 | + register_rest_field( |
| 29 | + $post_type, |
| 30 | + $field_name, |
| 31 | + array( |
| 32 | + 'schema' => $is_array |
| 33 | + ? array( |
| 34 | + 'type' => 'array', |
| 35 | + 'items' => array( 'type' => 'integer' ), |
| 36 | + 'context' => array( 'view', 'edit' ), |
| 37 | + 'default' => array(), |
| 38 | + ) |
| 39 | + : array( |
| 40 | + 'type' => 'integer', |
| 41 | + 'context' => array( 'view', 'edit' ), |
| 42 | + 'default' => 0, |
| 43 | + ), |
| 44 | + 'get_callback' => function ( $object ) use ( $field_name, $is_array ) { |
| 45 | + if ( ! isset( $object['id'] ) ) { |
| 46 | + return $is_array ? array() : 0; |
| 47 | + } |
| 48 | + $meta = get_post_meta( $object['id'], $field_name, true ); |
| 49 | + if ( $is_array ) { |
| 50 | + return ( empty( $meta ) || ! is_array( $meta ) ) ? array() : array_map( 'intval', $meta ); |
| 51 | + } |
| 52 | + return $meta ? intval( $meta ) : 0; |
| 53 | + }, |
| 54 | + 'update_callback' => function ( $value, $object ) use ( $field_name, $is_array ) { |
| 55 | + if ( $is_array ) { |
| 56 | + $value = is_array( $value ) ? array_map( 'intval', $value ) : ( $value ? array( intval( $value ) ) : array() ); |
| 57 | + } else { |
| 58 | + $value = intval( $value ); |
| 59 | + } |
| 60 | + update_post_meta( $object->ID, $field_name, $value ); |
| 61 | + return true; |
| 62 | + }, |
| 63 | + ) |
| 64 | + ); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +add_action( 'rest_api_init', 'gutenberg_register_media_edit_test_rest_fields' ); |
0 commit comments