Last active
July 16, 2020 21:48
-
-
Save ravewebdev/3440cd6a99958f70647a6a2fe0dc1f04 to your computer and use it in GitHub Desktop.
3.1. Set Up Custom Route
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
register_rest_route( 'rave-initiative/v1', '/initiative/(?P<id>[\d]+)', [ | |
'methods' => WP_REST_SERVER::EDITABLE, | |
'callback' => 'update_initiative', | |
'permission_callback' => 'check_initiative_permissions', | |
] ); | |
function check_initiative_permissions( WP_REST_Request $request ) : bool { | |
$post_id = $request->get_param( 'id' ) ?? 0; | |
if ( ! is_user_logged_in() ) { | |
return false; | |
} | |
$post = get_post( $post_id ); | |
if ( null === $post ) { | |
return false; | |
} | |
if ( current_user_can( 'edit_published_posts' ) ) { | |
return true; | |
} | |
return get_current_user_id() === $post->post_author; | |
} | |
function update_initiative( WP_REST_Request $request ) : WP_REST_Response { | |
$post_id = $request->get_param( 'id' ); | |
$block_id = $request->get_param( 'block_id' ); | |
$post_content = get_post_field( 'post_content', $post_id ); | |
$post_blocks = parse_blocks( $post_content ); | |
$post_blocks = array_map( function( $block ) use ( $block_id ) { | |
if ( 'rave/initiative-tracker' !== ( $block['blockName'] ?? '' ) || ( $block['attrs']['id'] ?? 0 ) !== $block_id ) { | |
return $block; | |
} | |
// Update block attributes here... | |
// E.g., $block['attrs']['some-attr'] = $attr_value; | |
return $block; | |
}, $post_blocks ); | |
wp_update_post( [ | |
'ID' => $post_id, | |
'post_content' => serialize_blocks( $post_blocks ), | |
] ); | |
return new WP_REST_Response( __( 'Initiative updated.', 'resource-tracker' ), 200 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment