|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Post Data source for Block Bindings. |
| 4 | + * |
| 5 | + * @since 6.9.0 |
| 6 | + * @package WordPress |
| 7 | + * @subpackage Block Bindings |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * Gets value for Post Data source. |
| 12 | + * |
| 13 | + * @since 6.9.0 |
| 14 | + * @access private |
| 15 | + * |
| 16 | + * @param array $source_args Array containing arguments used to look up the source value. |
| 17 | + * Example: array( "key" => "foo" ). |
| 18 | + * @param WP_Block $block_instance The block instance. |
| 19 | + * @return mixed The value computed for the source. |
| 20 | + */ |
| 21 | +function _block_bindings_post_data_get_value( array $source_args, $block_instance ) { |
| 22 | + if ( empty( $source_args['key'] ) ) { |
| 23 | + return null; |
| 24 | + } |
| 25 | + |
| 26 | + if ( empty( $block_instance->context['postId'] ) ) { |
| 27 | + return null; |
| 28 | + } |
| 29 | + $post_id = $block_instance->context['postId']; |
| 30 | + |
| 31 | + // If a post isn't public, we need to prevent unauthorized users from accessing the post data. |
| 32 | + $post = get_post( $post_id ); |
| 33 | + if ( ( ! is_post_publicly_viewable( $post ) && ! current_user_can( 'read_post', $post_id ) ) || post_password_required( $post ) ) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + if ( 'date' === $source_args['key'] ) { |
| 38 | + return esc_attr( get_the_date( 'c', $post_id ) ); |
| 39 | + } |
| 40 | + |
| 41 | + if ( 'modified' === $source_args['key'] ) { |
| 42 | + // Only return the modified date if it is later than the publishing date. |
| 43 | + if ( get_the_modified_date( 'U', $post_id ) > get_the_date( 'U', $post_id ) ) { |
| 44 | + return esc_attr( get_the_modified_date( 'c', $post_id ) ); |
| 45 | + } else { |
| 46 | + return ''; |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Registers Post Data source in the block bindings registry. |
| 53 | + * |
| 54 | + * @since 6.9.0 |
| 55 | + * @access private |
| 56 | + */ |
| 57 | +function _register_block_bindings_post_data_source() { |
| 58 | + register_block_bindings_source( |
| 59 | + 'core/post-data', |
| 60 | + array( |
| 61 | + 'label' => _x( 'Post Data', 'block bindings source' ), |
| 62 | + 'get_value_callback' => '_block_bindings_post_data_get_value', |
| 63 | + 'uses_context' => array( 'postId' ), |
| 64 | + ) |
| 65 | + ); |
| 66 | +} |
| 67 | + |
| 68 | +add_action( 'init', '_register_block_bindings_post_data_source' ); |
0 commit comments