diff --git a/packages/block-library/src/latest-posts/edit.js b/packages/block-library/src/latest-posts/edit.js index 8fa27ca78686c..2726b5e20d169 100644 --- a/packages/block-library/src/latest-posts/edit.js +++ b/packages/block-library/src/latest-posts/edit.js @@ -18,6 +18,7 @@ import { Spinner, ToggleControl, ToolbarGroup, + FormTokenField, } from '@wordpress/components'; import apiFetch from '@wordpress/api-fetch'; import { addQueryArgs } from '@wordpress/url'; @@ -96,6 +97,22 @@ class LatestPostsEdit extends Component { featuredImageSizeWidth, featuredImageSizeHeight, } = attributes; + const suggestions = categoriesList.reduce( + ( accumulator, category ) => ( { + ...accumulator, + [ category.name ]: category, + } ), + {} + ); + + const selectCategories = ( tokens ) => { + // Categories that are already will be objects, while new additions will be strings (the name). + // allCategories nomalizes the array so that they are all objects. + const allCategories = tokens.map( ( token ) => + typeof token === 'string' ? suggestions[ token ] : token + ); + setAttributes( { categories: allCategories } ); + }; const inspectorControls = ( @@ -209,23 +226,30 @@ class LatestPostsEdit extends Component { setAttributes( { order: value } ) } onOrderByChange={ ( value ) => setAttributes( { orderBy: value } ) } - onCategoryChange={ ( value ) => - setAttributes( { - categories: '' !== value ? value : undefined, - } ) - } onNumberOfItemsChange={ ( value ) => setAttributes( { postsToShow: value } ) } /> + { categoriesList.length > 0 && ( + ( { + id: item.id, + value: item.name || item.value, + } ) ) + } + suggestions={ Object.keys( suggestions ) } + onChange={ selectCategories } + /> + ) } { postLayout === 'grid' && ( { const { getEntityRecords, getMedia } = select( 'core' ); const { getSettings } = select( 'core/block-editor' ); const { imageSizes, imageDimensions } = getSettings(); + const catIds = + categories && categories.length > 0 + ? categories.map( ( cat ) => cat.id ) + : []; const latestPostsQuery = pickBy( { - categories, + categories: catIds, order, orderby: orderBy, per_page: postsToShow, diff --git a/packages/block-library/src/latest-posts/index.php b/packages/block-library/src/latest-posts/index.php index 6e96f10461231..346c4085b3c42 100644 --- a/packages/block-library/src/latest-posts/index.php +++ b/packages/block-library/src/latest-posts/index.php @@ -47,7 +47,7 @@ function render_block_core_latest_posts( $attributes ) { add_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 ); if ( isset( $attributes['categories'] ) ) { - $args['category'] = $attributes['categories']; + $args['category__in'] = array_column( $attributes['categories'], 'id' ); } $recent_posts = get_posts( $args ); @@ -182,7 +182,7 @@ function register_block_core_latest_posts() { 'type' => 'string', ), 'categories' => array( - 'type' => 'string', + 'type' => 'array', ), 'postsToShow' => array( 'type' => 'number',