PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.8.0
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.8.0
3.8.0 3.7.5 3.7.4 3.7.3 3.7.2 1-final 3.7.1 3.7.0 3.6.8 3.6.7 3.6.6 3.6.5 3.6.4 3.6.3 3.6.2 3.6.1 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 All 112 releases
templately / modules / mcp-abilities / Editor / GutenbergHeadlessInsert.php

GutenbergHeadlessInsert.php in Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! 3.8.0, at modules/mcp-abilities/Editor/GutenbergHeadlessInsert.php

73 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Headless (browser-free) Gutenberg content insertion into an EXISTING post
4 * (FR-006, FR-009, FR-014) — the new capability this feature introduces.
5 * Modeled on this environment's own proven sandbox-abilities technique
6 * (research.md §3), reimplemented fresh here.
7 *
8 * @package Templately\Modules\McpAbilities\Editor
9 */
10
11 namespace Templately\Modules\McpAbilities\Editor;
12
13 use WP_Error;
14
15 class GutenbergHeadlessInsert {
16
17 /**
18 * @param int $post_id
19 * @param string $block_markup Processed block markup to append (from the
20 * `/import/insert` route's response `content`, research.md §3).
21 * @param string $base_hash md5 of `post_content` as last read by the caller (FR-014).
22 * @return array|WP_Error
23 */
24 public static function insert( int $post_id, string $block_markup, string $base_hash ) {
25 $post = get_post( $post_id );
26
27 if ( ! $post ) {
28 return new WP_Error( 'not_found', __( 'Target post not found.', 'templately' ) );
29 }
30
31 // A post already carrying Elementor data is not a Gutenberg document.
32 if ( ! empty( get_post_meta( $post_id, '_elementor_edit_mode', true ) ) ) {
33 return new WP_Error( 'platform_mismatch', __( 'The target post is an Elementor document, not Gutenberg.', 'templately' ) );
34 }
35
36 $current_hash = self::hash( $post_id );
37
38 if ( $current_hash !== $base_hash ) {
39 return new WP_Error(
40 'conflict',
41 __( 'The post changed since it was last read. Re-read it and retry.', 'templately' ),
42 [ 'current_state_hash' => $current_hash ]
43 );
44 }
45
46 $blocks = parse_blocks( $post->post_content );
47 $new_blocks = parse_blocks( $block_markup );
48 $content = serialize_blocks( array_merge( $blocks, $new_blocks ) );
49
50 $updated = wp_update_post( [ 'ID' => $post_id, 'post_content' => $content ], true );
51
52 if ( is_wp_error( $updated ) ) {
53 return $updated;
54 }
55
56 return [
57 'target' => 'post',
58 'status' => 'success',
59 'post_id' => $post_id,
60 ];
61 }
62
63 /**
64 * @param int $post_id
65 * @return string
66 */
67 public static function hash( int $post_id ): string {
68 $post = get_post( $post_id );
69
70 return md5( $post ? (string) $post->post_content : '' );
71 }
72 }
73