Skip to content

Commit

Permalink
[LatestPosts] Fixes the excerpt length (#20313)
Browse files Browse the repository at this point in the history
* adds a filter that sets the excerpt length to what was set in the editor

* adds named function as excerpt filter and removes after use

* adds PHP doc to the new filter callback and global variable

* default to using an anonymous function since it appears that it can be remove and is not affecting theme set length

* revert to named function for excerpt length filter

* proper function names for Guternberg namespace

* lower default priority for the latest posts excerpt length filter
  • Loading branch information
draganescu authored and jorgefilipecosta committed Mar 2, 2020
1 parent 48076d0 commit 800b415
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/block-library/src/latest-posts/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,26 @@
* @package WordPress
*/

/**
* The excerpt length set by the Latest Posts core block
* set at render time and used by the block itself.
*
* @var int
*/
$block_core_latest_posts_excerpt_length = 0;

/**
* Callback for the excerpt_length filter used by
* the Latest Posts block at render time.
*
* @return int Returns the global $block_core_latest_posts_excerpt_length variable
* to allow the excerpt_length filter respect the Latest Block setting.
*/
function block_core_latest_posts_get_excerpt_length() {
global $block_core_latest_posts_excerpt_length;
return $block_core_latest_posts_excerpt_length;
}

/**
* Renders the `core/latest-posts` block on server.
*
Expand All @@ -13,6 +33,8 @@
* @return string Returns the post content with latest posts added.
*/
function render_block_core_latest_posts( $attributes ) {
global $block_core_latest_posts_excerpt_length;

$args = array(
'posts_per_page' => $attributes['postsToShow'],
'post_status' => 'publish',
Expand All @@ -21,6 +43,9 @@ function render_block_core_latest_posts( $attributes ) {
'suppress_filters' => false,
);

$block_core_latest_posts_excerpt_length = $attributes['excerptLength'];
add_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );

if ( isset( $attributes['categories'] ) ) {
$args['category'] = $attributes['categories'];
}
Expand Down Expand Up @@ -111,6 +136,8 @@ function render_block_core_latest_posts( $attributes ) {
$list_items_markup .= "</li>\n";
}

remove_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );

$class = 'wp-block-latest-posts wp-block-latest-posts__list';
if ( isset( $attributes['align'] ) ) {
$class .= ' align' . $attributes['align'];
Expand Down

0 comments on commit 800b415

Please sign in to comment.