Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
3.1. Set Up Custom Route
<?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