Custom block problem
-
I am a plugin developer and i made several custom blocs for the gutenberg editor.
Everything works correctly, including the preview in the editor, until the published page is re-opened in the editor: I get the error message:This page contains unexpected or invalid content
and the two buttons ‘Resolve’ and ‘Convert to HTML’The block definition of one of my custom blocks is:
function wppa_gutenberg_photo_block() { wp_register_script( 'wppa-gutenberg-photo', plugins_url( 'js/wppa-gutenberg-photo.js', __FILE__ ), array( 'wp-blocks', 'wp-element' ) ); register_block_type( 'wppa/gutenberg-photo', array( 'editor_script' => 'wppa-gutenberg-photo', ) ); } add_action( 'init', 'wppa_gutenberg_photo_block' );
The content of the page as seen by the classic editor is:
<!-- wp:wppa/gutenberg-photo --> <p>[photo 102]</p> <!-- /wp:wppa/gutenberg-photo -->
It looks as if Gutenberg suddely forgot that my blocktype wppa/gutenberg-photo exists…
I now added this code, to ‘manually’ change wppa/gutenberg-photo into wp:shortcode as if it were a wp shortcode:
// Fix Gutenberg bug function wppa_fix_gutenberg_shortcodes() { global $wpdb; if ( strpos( $_SERVER['REQUEST_URI'], '/wp-admin/post.php' ) !== false && strpos( $_SERVER['REQUEST_URI'], 'action=edit' ) !== false ) { $post = strval( intval ( $_GET['post'] ) ); // Get posts with wppa block_categories $posts = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d AND ( post_content LIKE %s OR post_content LIKE %s )", $post, '%' . $wpdb->esc_like( 'wp:wppa/gutenberg-photo' ) . '%', '%' . $wpdb->esc_like( 'wp:wppa/gutenberg-wppa' ) . '%' ), ARRAY_A ); if ( ! empty( $posts ) ) { foreach( $posts as $post ) { $new_content = str_replace( array( 'wp:wppa/gutenberg-photo', 'wp:wppa/gutenberg-wppa' ), 'wp:shortcode', $post['post_content'] ); $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_content = %s WHERE ID = %d", $new_content, $post['ID'] ) ); } } } } add_action( 'admin_init', 'wppa_fix_gutenberg_shortcodes' );
Now the error disappears.
This is obviously a workaround. I tried to declare my blocktype as shortcode but that conflicts with the generic wp shortcode blocktype.What am i doing wrong?
- The topic ‘Custom block problem’ is closed to new replies.