Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/media-utils/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Enhancements

- `MediaUploadModal`: Query filters on attachment taxonomy fields by the taxonomy. ([#86458](https://github.com/WordPress/gutenberg/pull/86458))

## 6.1.0 (2026-11-04)

### Enhancements
Expand Down
13 changes: 12 additions & 1 deletion packages/media-utils/src/components/media-upload-modal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { uploadMedia } from '../../utils/upload-media';
import { unlock } from '../../lock-unlock';
import { UploadStatusPopover } from './upload-status-popover';
import { useInvalidateAttachmentResolutions } from './use-invalidate-attachment-resolutions';
import { getTaxonomyQueryArgs } from './taxonomy-query';
import { useUploadStatus } from './use-upload-status';

const { useEntityRecordsWithPermissions } = unlock( coreDataPrivateApis );
Expand Down Expand Up @@ -281,6 +282,15 @@ export function MediaUploadModal( {
[ attachedToPostId, postType ]
);

// The attachment taxonomies, so that a filter on a taxonomy field reaches
// the query. Only requested when attachments have taxonomies at all.
const taxonomies = useSelect( ( select ) => {
const { getPostType, getTaxonomies } = select( coreStore );
return getPostType( 'attachment' )?.taxonomies?.length
? getTaxonomies( { type: 'attachment' } )
: undefined;
}, [] );

const [ selection, setSelection ] = useState< string[] >( () =>
getSelectionFromValue( value )
);
Expand Down Expand Up @@ -451,9 +461,10 @@ export function MediaUploadModal( {
orderby: view.sort?.field,
search: view.search,
_embed: 'author,wp:attached-to',
...getTaxonomyQueryArgs( view.filters, taxonomies ?? [] ),
...filters,
};
}, [ view, allowedTypes, attachedToPostId ] );
}, [ view, allowedTypes, attachedToPostId, taxonomies ] );

// Per-batch completion handler: auto-select uploaded items and refresh the grid.
const handleBatchComplete = useCallback(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type { Filter } from '@wordpress/dataviews';

/**
* The parts of a taxonomy record from core-data that the query needs.
*/
type QueryTaxonomy = {
slug: string;
rest_base?: string;
};

/**
* Returns the REST query arguments for a view's filters on taxonomy fields.
*
* A taxonomy field is one whose ID is the taxonomy's REST base: the property
* that holds an item's term IDs in its REST record, and the query parameter
* that filters items by them. Filters on other fields are left for the caller.
*
* - `is` and `isAny` match items with any of the terms.
* - `isAll` matches items with every one of the terms.
* - `isNot` and `isNone` match items with none of the terms.
*
* A filter matches the chosen terms only, not their child terms, because the
* REST API's `include_children` defaults to false. A filter with no terms
* leaves the query alone.
*
* The post list route has a copy of this function, so change both together.
*
* @param filters The view's filters.
* @param taxonomies The taxonomies of the entity, as `getTaxonomies()` returns them.
*
* @return The query arguments, such as `{ categories: [ 3, 4 ] }`.
*/
export function getTaxonomyQueryArgs(
filters: Filter[] = [],
taxonomies: QueryTaxonomy[] = []
): Record< string, unknown > {
const bases = new Set(
taxonomies.map( ( taxonomy ) => taxonomy.rest_base || taxonomy.slug )
);
const args: Record< string, unknown > = {};

for ( const filter of filters ) {
if ( ! bases.has( filter.field ) ) {
continue;
}

const terms = (
Array.isArray( filter.value ) ? filter.value : [ filter.value ]
).filter(
( term ) => term !== undefined && term !== null && term !== ''
);

if ( ! terms.length ) {
continue;
}

switch ( filter.operator ) {
case 'is':
case 'isAny':
args[ filter.field ] = terms;
break;
case 'isAll':
args[ filter.field ] = { terms, operator: 'AND' };
break;
case 'isNot':
case 'isNone':
args[ `${ filter.field }_exclude` ] = terms;
break;
}
}

return args;
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ const POST_TYPES: Record< string, unknown > = {
page: { labels: { uploaded_to_this_item: 'Uploaded to this page' } },
// A post type that never set the label.
cpt: { labels: {} },
attachment: { labels: {}, taxonomies: [ 'genre' ] },
};

const TAXONOMIES = [ { slug: 'genre', rest_base: 'genres' } ];

vi.mock( import( '@wordpress/core-data' ), async () => {
const { __dangerousOptInToUnstableAPIsOnlyForCoreModules } =
await import( '@wordpress/private-apis' );
Expand Down Expand Up @@ -101,6 +104,7 @@ function renderModal(
reducer: ( state = {} ) => state,
selectors: {
getPostType: ( state: unknown, slug: string ) => POST_TYPES[ slug ],
getTaxonomies: () => TAXONOMIES,
},
} );

Expand Down Expand Up @@ -623,6 +627,27 @@ describe( 'MediaUploadModal', () => {
} );
} );

it( 'queries a filter on a taxonomy field by the taxonomy', async () => {
renderModal(
{},
{
filters: [
{ field: 'genres', operator: 'isNone', value: [ 3 ] },
],
}
);

await waitFor( () => {
expect(
mockUseEntityRecordsWithPermissions
).toHaveBeenLastCalledWith(
'postType',
'attachment',
expect.objectContaining( { genres_exclude: [ 3 ] } )
);
} );
} );

it( 'updates the media query when the picker changes search', async () => {
const user = userEvent.setup();
const { registry } = renderModal();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest';
import { getTaxonomyQueryArgs } from '../taxonomy-query';

const TAXONOMIES = [
{ slug: 'category', rest_base: 'categories' },
{ slug: 'post_tag', rest_base: 'tags' },
{ slug: 'genre' },
{ slug: 'place', rest_base: 'places', hierarchical: true },
];

describe( 'getTaxonomyQueryArgs', () => {
it( 'queries items with any of the terms', () => {
expect(
getTaxonomyQueryArgs(
[ { field: 'categories', operator: 'isAny', value: [ 3, 4 ] } ],
TAXONOMIES
)
).toEqual( { categories: [ 3, 4 ] } );
} );

it( 'queries items with every one of the terms', () => {
expect(
getTaxonomyQueryArgs(
[ { field: 'tags', operator: 'isAll', value: [ 5, 6 ] } ],
TAXONOMIES
)
).toEqual( { tags: { terms: [ 5, 6 ], operator: 'AND' } } );
} );

it( 'queries items with none of the terms', () => {
expect(
getTaxonomyQueryArgs(
[ { field: 'tags', operator: 'isNone', value: [ 7 ] } ],
TAXONOMIES
)
).toEqual( { tags_exclude: [ 7 ] } );
} );

it( 'leaves `include_children` at the REST default of false', () => {
expect(
getTaxonomyQueryArgs(
[
{ field: 'places', operator: 'isAny', value: [ 9 ] },
{ field: 'places', operator: 'isNone', value: [ 10 ] },
],
TAXONOMIES
)
).toEqual( { places: [ 9 ], places_exclude: [ 10 ] } );
} );

it( 'takes a single term for `is` and `isNot`', () => {
expect(
getTaxonomyQueryArgs(
[
{ field: 'categories', operator: 'is', value: 3 },
{ field: 'tags', operator: 'isNot', value: 7 },
],
TAXONOMIES
)
).toEqual( { categories: [ 3 ], tags_exclude: [ 7 ] } );
} );

it( 'combines filters on several taxonomies', () => {
expect(
getTaxonomyQueryArgs(
[
{ field: 'categories', operator: 'isAny', value: [ 3 ] },
{ field: 'tags', operator: 'isNone', value: [ 7 ] },
],
TAXONOMIES
)
).toEqual( { categories: [ 3 ], tags_exclude: [ 7 ] } );
} );

it( 'uses the slug of a taxonomy with no REST base', () => {
expect(
getTaxonomyQueryArgs(
[ { field: 'genre', operator: 'isAny', value: [ 8 ] } ],
TAXONOMIES
)
).toEqual( { genre: [ 8 ] } );
} );

it( 'leaves the query alone for a filter with no terms', () => {
expect(
getTaxonomyQueryArgs(
[
{ field: 'categories', operator: 'isAny', value: [] },
{ field: 'tags', operator: 'isAny', value: undefined },
],
TAXONOMIES
)
).toEqual( {} );
} );

it( 'ignores filters on fields that are not taxonomies', () => {
expect(
getTaxonomyQueryArgs(
[
{ field: 'author', operator: 'isAny', value: [ 1 ] },
{ field: 'post_tag', operator: 'isAny', value: [ 5 ] },
],
TAXONOMIES
)
).toEqual( {} );
} );
} );
10 changes: 9 additions & 1 deletion routes/post-list/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,15 @@ export const route = {
}

// Otherwise, fetch the first post from the filtered query
const query = viewToQuery( view, params.type );
const postType = await resolveSelect( coreStore ).getPostType(
params.type
);
const taxonomies = postType?.taxonomies?.length
? await resolveSelect( coreStore ).getTaxonomies( {
type: params.type,
} )
: [];
const query = viewToQuery( view, params.type, taxonomies ?? [] );
const posts = await resolveSelect( coreStore ).getEntityRecords(
'postType',
params.type,
Expand Down
14 changes: 12 additions & 2 deletions routes/post-list/stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,19 @@ function PostListView( {
}
};

const hasTaxonomies = !! postTypeObject?.taxonomies?.length;
const taxonomies = useSelect(
( select ) =>
hasTaxonomies
? select( coreStore ).getTaxonomies( {
type: postType,
} )
: undefined,
[ hasTaxonomies, postType ]
);
const postTypeQuery = useMemo(
() => viewToQuery( view, postType ),
[ view, postType ]
() => viewToQuery( view, postType, taxonomies ?? [] ),
[ view, postType, taxonomies ]
);
const {
records: posts,
Expand Down
74 changes: 74 additions & 0 deletions routes/post-list/taxonomy-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { Filter } from '@wordpress/dataviews';

/**
* The parts of a taxonomy record from core-data that the query needs.
*/
type QueryTaxonomy = {
slug: string;
rest_base?: string;
};

/**
* Returns the REST query arguments for a view's filters on taxonomy fields.
*
* A taxonomy field is one whose ID is the taxonomy's REST base: the property
* that holds an item's term IDs in its REST record, and the query parameter
* that filters items by them. Filters on other fields are left for the caller.
*
* - `is` and `isAny` match items with any of the terms.
* - `isAll` matches items with every one of the terms.
* - `isNot` and `isNone` match items with none of the terms.
*
* A filter matches the chosen terms only, not their child terms, because the
* REST API's `include_children` defaults to false. A filter with no terms
* leaves the query alone.
*
* The media upload modal in `@wordpress/media-utils` has a copy of this
* function, so change both together.
*
* @param filters The view's filters.
* @param taxonomies The taxonomies of the entity, as `getTaxonomies()` returns them.
*
* @return The query arguments, such as `{ categories: [ 3, 4 ] }`.
*/
export function getTaxonomyQueryArgs(
filters: Filter[] = [],
taxonomies: QueryTaxonomy[] = []
): Record< string, unknown > {
const bases = new Set(
taxonomies.map( ( taxonomy ) => taxonomy.rest_base || taxonomy.slug )
);
const args: Record< string, unknown > = {};

for ( const filter of filters ) {
if ( ! bases.has( filter.field ) ) {
continue;
}

const terms = (
Array.isArray( filter.value ) ? filter.value : [ filter.value ]
).filter(
( term ) => term !== undefined && term !== null && term !== ''
);

if ( ! terms.length ) {
continue;
}

switch ( filter.operator ) {
case 'is':
case 'isAny':
args[ filter.field ] = terms;
break;
case 'isAll':
args[ filter.field ] = { terms, operator: 'AND' };
break;
case 'isNot':
case 'isNone':
args[ `${ filter.field }_exclude` ] = terms;
break;
}
}

return args;
}
Loading
Loading