@@ -102,28 +102,46 @@ function do_blocks( $content ) {
102
102
global $ wp_registered_blocks ;
103
103
104
104
// Extract the blocks from the post content.
105
- $ matcher = '/<!--\s*wp:([a-z](?:[a-z0-9\/]+)*)\s+((?:(?!-->).)*)\s*\/?-->(?:.*?<!--\s*\/wp:\g1\s+-->)?/s ' ;
105
+ $ matcher = '# ' . join ( '' , array (
106
+ '(?P<opener><!--\s* ' ,
107
+ 'wp:(?P<block_name>[a-z](?:[a-z0-9/]+)*)\s+ ' ,
108
+ '(?P<attributes>(?:(?!-->).)*) ' ,
109
+ '\s*/?-->\n?) ' ,
110
+ '(?: ' ,
111
+ '(?P<content>.*?) ' ,
112
+ '(?P<closer><!--\s*/wp:\g{block_name}\s+-->\n?) ' ,
113
+ ')? ' ,
114
+ ) ) . '#s ' ;
106
115
preg_match_all ( $ matcher , $ content , $ matches , PREG_OFFSET_CAPTURE );
107
116
108
117
$ new_content = $ content ;
118
+ $ offset_differential = 0 ;
109
119
foreach ( $ matches [0 ] as $ index => $ block_match ) {
110
- $ block_name = $ matches [1 ][ $ index ][0 ];
111
- // do nothing if the block is not registered.
112
- if ( ! isset ( $ wp_registered_blocks [ $ block_name ] ) ) {
113
- continue ;
114
- }
120
+ $ block_name = $ matches ['block_name ' ][ $ index ][0 ];
121
+
122
+ $ output = '' ;
123
+ if ( isset ( $ wp_registered_blocks [ $ block_name ] ) ) {
124
+ $ block_attributes_string = $ matches ['attributes ' ][ $ index ][0 ];
125
+ $ block_attributes = parse_block_attributes ( $ block_attributes_string );
115
126
116
- $ block_markup = $ block_match [0 ];
117
- $ block_attributes_string = $ matches [2 ][ $ index ][0 ];
118
- $ block_attributes = parse_block_attributes ( $ block_attributes_string );
127
+ // Call the block's render function to generate the dynamic output.
128
+ $ output = call_user_func ( $ wp_registered_blocks [ $ block_name ]['render ' ], $ block_attributes );
129
+ } elseif ( isset ( $ matches ['content ' ][ $ index ][0 ] ) ) {
130
+ $ output = $ matches ['content ' ][ $ index ][0 ];
131
+ }
119
132
120
- // Call the block's render function to generate the dynamic output.
121
- $ output = call_user_func ( $ wp_registered_blocks [ $ block_name ]['render ' ], $ block_attributes );
133
+ // Replace the matched block with the static or dynamic output.
134
+ $ new_content = substr_replace (
135
+ $ new_content ,
136
+ $ output ,
137
+ $ block_match [1 ] - $ offset_differential ,
138
+ strlen ( $ block_match [0 ] )
139
+ );
122
140
123
- // Replace the matched block with the dynamic output .
124
- $ new_content = str_replace ( $ block_markup , $ output , $ new_content );
141
+ // Update offset for the next replacement .
142
+ $ offset_differential += strlen ( $ block_match [ 0 ] ) - strlen ( $ output );
125
143
}
126
144
127
145
return $ new_content ;
128
146
}
129
- add_filter ( 'the_content ' , 'do_blocks ' , 10 ); // BEFORE do_shortcode().
147
+ add_filter ( 'the_content ' , 'do_blocks ' , 9 ); // BEFORE do_shortcode() and wpautop ().
0 commit comments