Blocks: Parse blocks when displaying posts.

Posts containing blocks are now correctly handled when displaying on the front end, including dynamic blocks and nested blocks.

See #45109.


Built from https://develop.svn.wordpress.org/branches/5.0@43752


git-svn-id: http://core.svn.wordpress.org/branches/5.0@43581 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Gary Pendergast 2018-10-18 11:54:26 +00:00
parent f7d01b4e70
commit 798c2581b1
12 changed files with 769 additions and 6 deletions

View File

@ -113,6 +113,44 @@ function get_dynamic_block_names() {
return $dynamic_block_names;
}
/**
* Remove all dynamic blocks from the given content.
*
* @since 5.0.0
*
* @param string $content Content of the current post.
* @return string
*/
function strip_dynamic_blocks( $content ) {
return _recurse_strip_dynamic_blocks( parse_blocks( $content ) );
}
/**
* Helper function for strip_dynamic_blocks(), to recurse through the block tree.
*
* @since 5.0.0
* @access private
*
* @param array $blocks Array of blocks from parse_blocks().
* @return string HTML from the non-dynamic blocks.
*/
function _recurse_strip_dynamic_blocks( $blocks ) {
$clean_content = '';
$dynamic_blocks = get_dynamic_block_names();
foreach ( $blocks as $block ) {
if ( ! in_array( $block['blockName'], $dynamic_blocks ) ) {
if ( $block['innerBlocks'] ) {
$clean_content .= _recurse_strip_dynamic_blocks( $block['innerBlocks'] );
} else {
$clean_content .= $block['innerHTML'];
}
}
}
return $clean_content;
}
/**
* Parses blocks out of a content string.
*
@ -142,10 +180,85 @@ function parse_blocks( $content ) {
*
* @since 5.0.0
*
* @param string $parser_class Name of block parser class
* @param string $parser_class Name of block parser class.
*/
$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
$parser = new $parser_class();
return $parser->parse( $content );
}
/**
* Parses dynamic blocks out of `post_content` and re-renders them.
*
* @since 5.0.0
* @global WP_Post $post The post to edit.
*
* @param string $content Post content.
* @return string Updated post content.
*/
function do_blocks( $content ) {
$blocks = parse_blocks( $content );
return _recurse_do_blocks( $blocks, $blocks );
}
/**
* Helper function for do_blocks(), to recurse through the block tree.
*
* @since 5.0.0
* @access private
*
* @param array $blocks Array of blocks from parse_blocks().
* @param array $all_blocks The top level array of blocks.
* @return string The block HTML.
*/
function _recurse_do_blocks( $blocks, $all_blocks ) {
global $post;
/*
* Back up global post, to restore after render callback.
* Allows callbacks to run new WP_Query instances without breaking the global post.
*/
$global_post = $post;
$rendered_content = '';
$dynamic_blocks = get_dynamic_block_names();
foreach ( $blocks as $block ) {
$block = (array) $block;
if ( in_array( $block['blockName'], $dynamic_blocks ) ) {
// Find registered block type. We can assume it exists since we use the
// `get_dynamic_block_names` function as a source for pattern matching.
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
// Replace dynamic block with server-rendered output.
$block_content = $block_type->render( (array) $block['attrs'], $block['innerHTML'] );
} else if ( $block['innerBlocks'] ) {
$block_content = _recurse_do_blocks( $block['innerBlocks'], $blocks );
} else {
$block_content = $block['innerHTML'];
}
/**
* Filters the content of a single block.
*
* During the_content, each block is parsed and added to the output individually. This filter allows
* that content to be altered immediately before it's appended.
*
* @since 5.0.0
*
* @param string $block_content The block content about to be appended.
* @param array $block The full block, including name and attributes.
* @param array $all_blocks The array of all blocks being processed.
*/
$rendered_content .= apply_filters( 'do_block', $block_content, $block, $all_blocks );
// Restore global $post.
$post = $global_post;
}
// Strip remaining block comment demarcations.
$rendered_content = preg_replace( '/<!--\s+\/?wp:.*?-->/m', '', $rendered_content );
return $rendered_content;
}

View File

@ -0,0 +1,143 @@
<?php
/**
* Server-side rendering of the `core/archives` block.
*
* @package gutenberg
*/
/**
* Renders the `core/archives` block on server.
*
* @see WP_Widget_Archives
*
* @param array $attributes The block attributes.
*
* @return string Returns the post content with archives added.
*/
function render_block_core_archives( $attributes ) {
$show_post_count = ! empty( $attributes['showPostCounts'] );
$class = 'wp-block-archives';
if ( isset( $attributes['align'] ) ) {
$class .= " align{$attributes['align']}";
}
if ( isset( $attributes['className'] ) ) {
$class .= " {$attributes['className']}";
}
if ( ! empty( $attributes['displayAsDropdown'] ) ) {
$dropdown_id = esc_attr( uniqid( 'wp-block-archives-' ) );
$title = __( 'Archives', 'gutenberg' );
/** This filter is documented in wp-includes/widgets/class-wp-widget-archives.php */
$dropdown_args = apply_filters(
'widget_archives_dropdown_args',
array(
'type' => 'monthly',
'format' => 'option',
'show_post_count' => $show_post_count,
)
);
$dropdown_args['echo'] = 0;
$archives = wp_get_archives( $dropdown_args );
switch ( $dropdown_args['type'] ) {
case 'yearly':
$label = __( 'Select Year', 'gutenberg' );
break;
case 'monthly':
$label = __( 'Select Month', 'gutenberg' );
break;
case 'daily':
$label = __( 'Select Day', 'gutenberg' );
break;
case 'weekly':
$label = __( 'Select Week', 'gutenberg' );
break;
default:
$label = __( 'Select Post', 'gutenberg' );
break;
}
$label = esc_attr( $label );
$block_content = '<label class="screen-reader-text" for="' . $dropdown_id . '">' . $title . '</label>
<select id="' . $dropdown_id . '" name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value="">' . $label . '</option>' . $archives . '</select>';
$block_content = sprintf(
'<div class="%1$s">%2$s</div>',
esc_attr( $class ),
$block_content
);
} else {
/** This filter is documented in wp-includes/widgets/class-wp-widget-archives.php */
$archives_args = apply_filters(
'widget_archives_args',
array(
'type' => 'monthly',
'show_post_count' => $show_post_count,
)
);
$archives_args['echo'] = 0;
$archives = wp_get_archives( $archives_args );
$classnames = esc_attr( $class );
if ( empty( $archives ) ) {
$block_content = sprintf(
'<div class="%1$s">%2$s</div>',
$classnames,
__( 'No archives to show.', 'gutenberg' )
);
} else {
$block_content = sprintf(
'<ul class="%1$s">%2$s</ul>',
$classnames,
$archives
);
}
}
return $block_content;
}
/**
* Register archives block.
*/
function register_block_core_archives() {
register_block_type(
'core/archives',
array(
'attributes' => array(
'align' => array(
'type' => 'string',
),
'className' => array(
'type' => 'string',
),
'displayAsDropdown' => array(
'type' => 'boolean',
'default' => false,
),
'showPostCounts' => array(
'type' => 'boolean',
'default' => false,
),
),
'render_callback' => 'render_block_core_archives',
)
);
}
add_action( 'init', 'register_block_core_archives' );

View File

@ -0,0 +1,39 @@
<?php
/**
* Server-side rendering of the `core/block` block.
*
* @package gutenberg
*/
/**
* Renders the `core/block` block on server.
*
* @param array $attributes The block attributes.
*
* @return string Rendered HTML of the referenced block.
*/
function render_block_core_block( $attributes ) {
if ( empty( $attributes['ref'] ) ) {
return '';
}
$reusable_block = get_post( $attributes['ref'] );
if ( ! $reusable_block || 'wp_block' !== $reusable_block->post_type ) {
return '';
}
return do_blocks( $reusable_block->post_content );
}
register_block_type(
'core/block',
array(
'attributes' => array(
'ref' => array(
'type' => 'number',
),
),
'render_callback' => 'render_block_core_block',
)
);

View File

@ -0,0 +1,103 @@
<?php
/**
* Server-side rendering of the `core/categories` block.
*
* @package gutenberg
*/
/**
* Renders the `core/categories` block on server.
*
* @param array $attributes The block attributes.
*
* @return string Returns the categories list/dropdown markup.
*/
function render_block_core_categories( $attributes ) {
static $block_id = 0;
$block_id++;
$align = 'center';
if ( isset( $attributes['align'] ) && in_array( $attributes['align'], array( 'left', 'right', 'full' ), true ) ) {
$align = $attributes['align'];
}
$args = array(
'echo' => false,
'hierarchical' => ! empty( $attributes['showHierarchy'] ),
'orderby' => 'name',
'show_count' => ! empty( $attributes['showPostCounts'] ),
'title_li' => '',
);
if ( ! empty( $attributes['displayAsDropdown'] ) ) {
$id = 'wp-block-categories-' . $block_id;
$args['id'] = $id;
$args['show_option_none'] = __( 'Select Category', 'gutenberg' );
$wrapper_markup = '<div class="%1$s">%2$s</div>';
$items_markup = wp_dropdown_categories( $args );
$type = 'dropdown';
if ( ! is_admin() ) {
$wrapper_markup .= build_dropdown_script_block_core_categories( $id );
}
} else {
$wrapper_markup = '<ul class="%1$s">%2$s</ul>';
$items_markup = wp_list_categories( $args );
$type = 'list';
}
$class = "wp-block-categories wp-block-categories-{$type} align{$align}";
if ( isset( $attributes['className'] ) ) {
$class .= ' ' . $attributes['className'];
}
$block_content = sprintf(
$wrapper_markup,
esc_attr( $class ),
$items_markup
);
return $block_content;
}
/**
* Generates the inline script for a categories dropdown field.
*
* @param string $dropdown_id ID of the dropdown field.
*
* @return string Returns the dropdown onChange redirection script.
*/
function build_dropdown_script_block_core_categories( $dropdown_id ) {
ob_start();
?>
<script type='text/javascript'>
/* <![CDATA[ */
(function() {
var dropdown = document.getElementById( '<?php echo esc_js( $dropdown_id ); ?>' );
function onCatChange() {
if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) {
location.href = "<?php echo home_url(); ?>/?cat=" + dropdown.options[ dropdown.selectedIndex ].value;
}
}
dropdown.onchange = onCatChange;
})();
/* ]]> */
</script>
<?php
return ob_get_clean();
}
/**
* Registers the `core/categories` block on server.
*/
function register_block_core_categories() {
register_block_type(
'core/categories',
array(
'render_callback' => 'render_block_core_categories',
)
);
}
add_action( 'init', 'register_block_core_categories' );

View File

@ -0,0 +1,182 @@
<?php
/**
* Server-side rendering of the `core/latest-comments` block.
*
* @package gutenberg
*/
/**
* Get the post title.
*
* The post title is fetched and if it is blank then a default string is
* returned.
*
* Copied from `wp-admin/includes/template.php`, but we can't include that
* file because:
*
* 1. It causes bugs with test fixture generation and strange Docker 255 error
* codes.
* 2. It's in the admin; ideally we *shouldn't* be including files from the
* admin for a block's output. It's a very small/simple function as well,
* so duplicating it isn't too terrible.
*
* @since 3.3.0
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
* @return string The post title if set; "(no title)" if no title is set.
*/
function gutenberg_draft_or_post_title( $post = 0 ) {
$title = get_the_title( $post );
if ( empty( $title ) ) {
$title = __( '(no title)', 'gutenberg' );
}
return esc_html( $title );
}
/**
* Renders the `core/latest-comments` block on server.
*
* @param array $attributes The block attributes.
*
* @return string Returns the post content with latest comments added.
*/
function gutenberg_render_block_core_latest_comments( $attributes = array() ) {
// This filter is documented in wp-includes/widgets/class-wp-widget-recent-comments.php.
$comments = get_comments(
apply_filters(
'widget_comments_args',
array(
'number' => $attributes['commentsToShow'],
'status' => 'approve',
'post_status' => 'publish',
)
)
);
$list_items_markup = '';
if ( ! empty( $comments ) ) {
// Prime the cache for associated posts. This is copied from \WP_Widget_Recent_Comments::widget().
$post_ids = array_unique( wp_list_pluck( $comments, 'comment_post_ID' ) );
_prime_post_caches( $post_ids, strpos( get_option( 'permalink_structure' ), '%category%' ), false );
foreach ( $comments as $comment ) {
$list_items_markup .= '<li class="wp-block-latest-comments__comment">';
if ( $attributes['displayAvatar'] ) {
$avatar = get_avatar(
$comment,
48,
'',
'',
array(
'class' => 'wp-block-latest-comments__comment-avatar',
)
);
if ( $avatar ) {
$list_items_markup .= $avatar;
}
}
$list_items_markup .= '<article>';
$list_items_markup .= '<footer class="wp-block-latest-comments__comment-meta">';
$author_url = get_comment_author_url( $comment );
if ( empty( $author_url ) && ! empty( $comment->user_id ) ) {
$author_url = get_author_posts_url( $comment->user_id );
}
$author_markup = '';
if ( $author_url ) {
$author_markup .= '<a class="wp-block-latest-comments__comment-author" href="' . esc_url( $author_url ) . '">' . get_comment_author( $comment ) . '</a>';
} else {
$author_markup .= '<span class="wp-block-latest-comments__comment-author">' . get_comment_author( $comment ) . '</span>';
}
// `_draft_or_post_title` calls `esc_html()` so we don't need to wrap that call in
// `esc_html`.
$post_title = '<a class="wp-block-latest-comments__comment-link" href="' . esc_url( get_comment_link( $comment ) ) . '">' . gutenberg_draft_or_post_title( $comment->comment_post_ID ) . '</a>';
$list_items_markup .= sprintf(
/* translators: 1: author name (inside <a> or <span> tag, based on if they have a URL), 2: post title related to this comment */
__( '%1$s on %2$s', 'gutenberg' ),
$author_markup,
$post_title
);
if ( $attributes['displayDate'] ) {
$list_items_markup .= sprintf(
'<time datetime="%1$s" class="wp-block-latest-comments__comment-date">%2$s</time>',
esc_attr( get_comment_date( 'c', $comment ) ),
date_i18n( get_option( 'date_format' ), get_comment_date( 'U', $comment ) )
);
}
$list_items_markup .= '</footer>';
if ( $attributes['displayExcerpt'] ) {
$list_items_markup .= '<div class="wp-block-latest-comments__comment-excerpt">' . wpautop( get_comment_excerpt( $comment ) ) . '</div>';
}
$list_items_markup .= '</article></li>';
}
}
$class = 'wp-block-latest-comments';
if ( $attributes['align'] ) {
$class .= " align{$attributes['align']}";
}
if ( $attributes['displayAvatar'] ) {
$class .= ' has-avatars';
}
if ( $attributes['displayDate'] ) {
$class .= ' has-dates';
}
if ( $attributes['displayExcerpt'] ) {
$class .= ' has-excerpts';
}
if ( empty( $comments ) ) {
$class .= ' no-comments';
}
$classnames = esc_attr( $class );
$block_content = ! empty( $comments ) ? sprintf(
'<ol class="%1$s">%2$s</ol>',
$classnames,
$list_items_markup
) : sprintf(
'<div class="%1$s">%2$s</div>',
$classnames,
__( 'No comments to show.', 'gutenberg' )
);
return $block_content;
}
register_block_type(
'core/latest-comments',
array(
'attributes' => array(
'className' => array(
'type' => 'string',
),
'commentsToShow' => array(
'type' => 'number',
'default' => 5,
'minimum' => 1,
'maximum' => 100,
),
'displayAvatar' => array(
'type' => 'boolean',
'default' => true,
),
'displayDate' => array(
'type' => 'boolean',
'default' => true,
),
'displayExcerpt' => array(
'type' => 'boolean',
'default' => true,
),
'align' => array(
'type' => 'string',
'enum' => array( 'center', 'left', 'right', 'wide', 'full', '' ),
),
),
'render_callback' => 'gutenberg_render_block_core_latest_comments',
)
);

View File

@ -0,0 +1,125 @@
<?php
/**
* Server-side rendering of the `core/latest-posts` block.
*
* @package gutenberg
*/
/**
* Renders the `core/latest-posts` block on server.
*
* @param array $attributes The block attributes.
*
* @return string Returns the post content with latest posts added.
*/
function render_block_core_latest_posts( $attributes ) {
$recent_posts = wp_get_recent_posts(
array(
'numberposts' => $attributes['postsToShow'],
'post_status' => 'publish',
'order' => $attributes['order'],
'orderby' => $attributes['orderBy'],
'category' => $attributes['categories'],
)
);
$list_items_markup = '';
foreach ( $recent_posts as $post ) {
$post_id = $post['ID'];
$title = get_the_title( $post_id );
if ( ! $title ) {
$title = __( '(Untitled)', 'gutenberg' );
}
$list_items_markup .= sprintf(
'<li><a href="%1$s">%2$s</a>',
esc_url( get_permalink( $post_id ) ),
esc_html( $title )
);
if ( isset( $attributes['displayPostDate'] ) && $attributes['displayPostDate'] ) {
$list_items_markup .= sprintf(
'<time datetime="%1$s" class="wp-block-latest-posts__post-date">%2$s</time>',
esc_attr( get_the_date( 'c', $post_id ) ),
esc_html( get_the_date( '', $post_id ) )
);
}
$list_items_markup .= "</li>\n";
}
$class = 'wp-block-latest-posts';
if ( isset( $attributes['align'] ) ) {
$class .= ' align' . $attributes['align'];
}
if ( isset( $attributes['postLayout'] ) && 'grid' === $attributes['postLayout'] ) {
$class .= ' is-grid';
}
if ( isset( $attributes['columns'] ) && 'grid' === $attributes['postLayout'] ) {
$class .= ' columns-' . $attributes['columns'];
}
if ( isset( $attributes['className'] ) ) {
$class .= ' ' . $attributes['className'];
}
$block_content = sprintf(
'<ul class="%1$s">%2$s</ul>',
esc_attr( $class ),
$list_items_markup
);
return $block_content;
}
/**
* Registers the `core/latest-posts` block on server.
*/
function register_block_core_latest_posts() {
register_block_type(
'core/latest-posts',
array(
'attributes' => array(
'categories' => array(
'type' => 'string',
),
'className' => array(
'type' => 'string',
),
'postsToShow' => array(
'type' => 'number',
'default' => 5,
),
'displayPostDate' => array(
'type' => 'boolean',
'default' => false,
),
'postLayout' => array(
'type' => 'string',
'default' => 'list',
),
'columns' => array(
'type' => 'number',
'default' => 3,
),
'align' => array(
'type' => 'string',
),
'order' => array(
'type' => 'string',
'default' => 'desc',
),
'orderBy' => array(
'type' => 'string',
'default' => 'date',
),
),
'render_callback' => 'render_block_core_latest_posts',
)
);
}
add_action( 'init', 'register_block_core_latest_posts' );

View File

@ -0,0 +1,32 @@
<?php
/**
* Server-side rendering of the `core/shortcode` block.
*
* @package gutenberg
*/
/**
* Performs wpautop() on the shortcode block content.
*
* @param array $attributes The block attributes.
* @param string $content The block content.
*
* @return string Returns the block content.
*/
function render_block_core_shortcode( $attributes, $content ) {
return wpautop( $content );
}
/**
* Registers the `core/shortcode` block on server.
*/
function register_block_core_shortcode() {
register_block_type(
'core/shortcode',
array(
'render_callback' => 'render_block_core_shortcode',
)
);
}
add_action( 'init', 'register_block_core_shortcode' );

View File

@ -306,7 +306,14 @@ class WP_Block_Parser {
* block and add it as a new innerBlock to the parent
*/
$stack_top = array_pop( $this->stack );
$stack_top->block->innerHTML .= substr( $this->document, $stack_top->prev_offset, $start_offset - $stack_top->prev_offset );
$html = substr( $this->document, $stack_top->prev_offset, $start_offset - $stack_top->prev_offset );
if ( $stack_top->block->innerBlocks ) {
$stack_top->block->innerBlocks[] = (array) $this->freeform( $html );
} else {
$stack_top->block->innerHTML = $html;
}
$stack_top->prev_offset = $start_offset + $token_length;
$this->add_inner_block(
@ -440,8 +447,8 @@ class WP_Block_Parser {
*/
function add_inner_block( WP_Block_Parser_Block $block, $token_start, $token_length, $last_offset = null ) {
$parent = $this->stack[ count( $this->stack ) - 1 ];
$parent->block->innerBlocks[] = $block;
$parent->block->innerHTML .= substr( $this->document, $parent->prev_offset, $token_start - $parent->prev_offset );
$parent->block->innerBlocks[] = (array) $this->freeform( substr( $this->document, $parent->prev_offset, $token_start - $parent->prev_offset ) );
$parent->block->innerBlocks[] = (array) $block;
$parent->prev_offset = $last_offset ? $last_offset : $token_start + $token_length;
}
@ -456,10 +463,16 @@ class WP_Block_Parser {
$stack_top = array_pop( $this->stack );
$prev_offset = $stack_top->prev_offset;
$stack_top->block->innerHTML .= isset( $end_offset )
$html = isset( $end_offset )
? substr( $this->document, $prev_offset, $end_offset - $prev_offset )
: substr( $this->document, $prev_offset );
if ( $stack_top->block->innerBlocks ) {
$stack_top->block->innerBlocks[] = (array) $this->freeform( $html );
} else {
$stack_top->block->innerHTML = $html;
}
if ( isset( $stack_top->leading_html_start ) ) {
$this->output[] = (array) self::freeform( substr(
$this->document,

View File

@ -171,6 +171,7 @@ add_filter( 'the_title', 'wptexturize' );
add_filter( 'the_title', 'convert_chars' );
add_filter( 'the_title', 'trim' );
add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'wpautop' );

View File

@ -442,6 +442,11 @@ function wpautop( $pee, $br = true ) {
if ( trim($pee) === '' )
return '';
// We don't need to autop posts with blocks in them.
if ( has_blocks( $pee ) ) {
return $pee;
}
// Just to make things a little easier, pad the end.
$pee = $pee . "\n";
@ -3371,6 +3376,7 @@ function wp_trim_excerpt( $text = '' ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
$text = strip_dynamic_blocks( $text );
/** This filter is documented in wp-includes/post-template.php */
$text = apply_filters( 'the_content', $text );

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.0-alpha-43751';
$wp_version = '5.0-alpha-43752';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.

View File

@ -247,6 +247,12 @@ require( ABSPATH . WPINC . '/class-wp-block-type.php' );
require( ABSPATH . WPINC . '/class-wp-block-type-registry.php' );
require( ABSPATH . WPINC . '/class-wp-block-parser.php' );
require( ABSPATH . WPINC . '/blocks.php' );
require( ABSPATH . WPINC . '/blocks/archives.php' );
require( ABSPATH . WPINC . '/blocks/block.php' );
require( ABSPATH . WPINC . '/blocks/categories.php' );
require( ABSPATH . WPINC . '/blocks/latest-comments.php' );
require( ABSPATH . WPINC . '/blocks/latest-posts.php' );
require( ABSPATH . WPINC . '/blocks/shortcode.php' );
$GLOBALS['wp_embed'] = new WP_Embed();