REST API: allow overriding excerpt length.

This can be used by the excerpt block in the editor to change the excerpt length without filtering `excerpt_length` in a conflicting way. This enhancement still needs a corresponding change on the Gutenberg side.

Props swissspidy, antonvlasenko, mukesh27, azaozz, andraganescu, timothyblynjacobs.
Fixes #59043.
Built from https://develop.svn.wordpress.org/trunk@58065


git-svn-id: http://core.svn.wordpress.org/trunk@57530 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Pascal Birchler 2024-04-30 09:33:05 +00:00
parent b2da8bbcc9
commit c3961d849c
2 changed files with 28 additions and 1 deletions

View File

@ -97,6 +97,12 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
$get_item_args = array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
);
if ( isset( $schema['properties']['excerpt'] ) ) {
$get_item_args['excerpt_length'] = array(
'description' => __( 'Override the default excerpt length.' ),
'type' => 'integer',
);
}
if ( isset( $schema['properties']['password'] ) ) {
$get_item_args['password'] = array(
'description' => __( 'The password for the post if it is password protected.' ),
@ -1872,6 +1878,19 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
}
if ( rest_is_field_included( 'excerpt', $fields ) ) {
if ( isset( $request['excerpt_length'] ) ) {
$excerpt_length = $request['excerpt_length'];
$override_excerpt_length = static function () use ( $excerpt_length ) {
return $excerpt_length;
};
add_filter(
'excerpt_length',
$override_excerpt_length,
20
);
}
/** This filter is documented in wp-includes/post-template.php */
$excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
@ -1883,6 +1902,14 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
'rendered' => post_password_required( $post ) ? '' : $excerpt,
'protected' => (bool) $post->post_password,
);
if ( isset( $override_excerpt_length ) ) {
remove_filter(
'excerpt_length',
$override_excerpt_length,
20
);
}
}
if ( $has_password_filter ) {

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.6-alpha-58064';
$wp_version = '6.6-alpha-58065';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.