Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Block Library - Query Loop]: Add support for custom taxonomies filtering #38063

Merged
merged 8 commits into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 34 additions & 8 deletions lib/compat/wordpress-6.0/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,41 @@ function gutenberg_build_query_vars_from_query_block( $block, $page ) {
$query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset;
$query['posts_per_page'] = $per_page;
}
if ( ! empty( $block->context['query']['categoryIds'] ) ) {
$term_ids = array_map( 'intval', $block->context['query']['categoryIds'] );
$term_ids = array_filter( $term_ids );
$query['category__in'] = $term_ids;

// We need to migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility.
if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) {
$tax_query = array();
if ( ! empty( $block->context['query']['categoryIds'] ) ) {
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $block->context['query']['categoryIds'],
'include_children' => false,
);
}
if ( ! empty( $block->context['query']['tagIds'] ) ) {
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $block->context['query']['tagIds'],
'include_children' => false,
);
}
$query['tax_query'] = $tax_query;
}
if ( ! empty( $block->context['query']['tagIds'] ) ) {
$term_ids = array_map( 'intval', $block->context['query']['tagIds'] );
$term_ids = array_filter( $term_ids );
$query['tag__in'] = $term_ids;
if ( ! empty( $block->context['query']['taxQuery'] ) ) {
$query['tax_query'] = array();
foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) {
if ( ! empty( $terms ) ) {
$term_ids = array_map( 'intval', $terms );
$term_ids = array_filter( $term_ids );

$query['tax_query'][] = array(
'taxonomy' => $taxonomy,
'terms' => $terms,
'include_children' => false,

ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
);
}
}
}
if (
isset( $block->context['query']['order'] ) &&
Expand Down
30 changes: 27 additions & 3 deletions packages/block-library/src/post-template/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export default function PostTemplateEdit( {
exclude,
sticky,
inherit,
taxQuery,
} = {},
queryContext = [ { page: 1 } ],
templateSlug,
Expand All @@ -90,15 +91,37 @@ export default function PostTemplateEdit( {

const { posts, blocks } = useSelect(
( select ) => {
const { getEntityRecords } = select( coreStore );
const { getEntityRecords, getTaxonomies } = select( coreStore );
const { getBlocks } = select( blockEditorStore );
const taxonomies = getTaxonomies( {
type: postType,
per_page: -1,
context: 'view',
} );
const query = {
offset: perPage ? perPage * ( page - 1 ) + offset : 0,
categories: categoryIds,
tags: tagIds,
order,
orderby: orderBy,
};
if ( taxQuery ) {
// We have to build the tax query for the REST API and use as
// keys the taxonomies `rest_base` with the `term ids` as values.
const builtTaxQuery = Object.entries( taxQuery ).reduce(
( accumulator, [ taxonomySlug, terms ] ) => {
const taxonomy = taxonomies?.find(
( { slug } ) => slug === taxonomySlug
);
if ( taxonomy?.rest_base ) {
accumulator[ taxonomy?.rest_base ] = terms;
}
return accumulator;
},
{}
);
if ( !! Object.keys( builtTaxQuery ).length ) {
Object.assign( query, builtTaxQuery );
}
}
if ( perPage ) {
query.per_page = perPage;
}
Expand Down Expand Up @@ -146,6 +169,7 @@ export default function PostTemplateEdit( {
sticky,
inherit,
templateSlug,
taxQuery,
]
);
const blockContexts = useMemo(
Expand Down
3 changes: 2 additions & 1 deletion packages/block-library/src/query/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"search": "",
"exclude": [],
"sticky": "",
"inherit": true
"inherit": true,
"taxQuery": null
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
}
},
"tagName": {
Expand Down
170 changes: 45 additions & 125 deletions packages/block-library/src/query/edit/inspector-controls/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,54 +9,33 @@ import { debounce } from 'lodash';
import {
PanelBody,
TextControl,
FormTokenField,
SelectControl,
RangeControl,
ToggleControl,
Notice,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import {
InspectorControls,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { useDispatch } from '@wordpress/data';
import { useEffect, useState, useCallback } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';

/**
* Internal dependencies
*/
import OrderControl from './order-control';
import AuthorControl from './author-control';
import { getEntitiesInfo, usePostTypes } from '../../utils';
import { MAX_FETCHED_TERMS } from '../../constants';
import TaxonomyControls from './taxonomy-controls';
import { usePostTypes } from '../../utils';

const stickyOptions = [
{ label: __( 'Include' ), value: '' },
{ label: __( 'Exclude' ), value: 'exclude' },
{ label: __( 'Only' ), value: 'only' },
];

// Helper function to get the term id based on user input in terms `FormTokenField`.
const getTermIdByTermValue = ( termsMappedByName, termValue ) => {
// First we check for exact match by `term.id` or case sensitive `term.name` match.
const termId = termValue?.id || termsMappedByName[ termValue ]?.id;
if ( termId ) return termId;
/**
* Here we make an extra check for entered terms in a non case sensitive way,
* to match user expectations, due to `FormTokenField` behaviour that shows
* suggestions which are case insensitive.
*
* Although WP tries to discourage users to add terms with the same name (case insensitive),
* it's still possible if you manually change the name, as long as the terms have different slugs.
* In this edge case we always apply the first match from the terms list.
*/
const termValueLower = termValue.toLocaleLowerCase();
for ( const term in termsMappedByName ) {
if ( term.toLocaleLowerCase() === termValueLower ) {
return termsMappedByName[ term ].id;
}
}
};

export default function QueryInspectorControls( {
attributes: { query, displayLayout },
setQuery,
Expand All @@ -69,64 +48,56 @@ export default function QueryInspectorControls( {
postType,
sticky,
inherit,
taxQuery,
} = query;
const [ showCategories, setShowCategories ] = useState( true );
const [ showTags, setShowTags ] = useState( true );
const [ showSticky, setShowSticky ] = useState( postType === 'post' );
const { postTypesTaxonomiesMap, postTypesSelectOptions } = usePostTypes();
const { categories, tags } = useSelect( ( select ) => {
const { getEntityRecords } = select( coreStore );
const termsQuery = { per_page: MAX_FETCHED_TERMS };
const _categories = getEntityRecords(
'taxonomy',
'category',
termsQuery
);
const _tags = getEntityRecords( 'taxonomy', 'post_tag', termsQuery );
return {
categories: getEntitiesInfo( _categories ),
tags: getEntitiesInfo( _tags ),
};
}, [] );
useEffect( () => {
if ( ! postTypesTaxonomiesMap ) return;
const postTypeTaxonomies = postTypesTaxonomiesMap[ postType ];
setShowCategories( postTypeTaxonomies.includes( 'category' ) );
setShowTags( postTypeTaxonomies.includes( 'post_tag' ) );
}, [ postType, postTypesTaxonomiesMap ] );
useEffect( () => {
setShowSticky( postType === 'post' );
}, [ postType ] );
const { __unstableMarkNextChangeAsNotPersistent } = useDispatch(
blockEditorStore
);
// We need to migrate `categoryIds` and `tagIds` to `tax_query`.
// TODO: We could probably use the `deprecations` API but it
// doesn't support dynamic blocks deprecations properly.
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
useEffect( () => {
if ( query.categoryIds?.length || query.tagIds?.length ) {
const updateObj = { categoryIds: [], tagIds: [] };
updateObj.taxQuery = {
category: !! query.categoryIds?.length
? query.categoryIds
: undefined,
post_tag: !! query.tagIds?.length ? query.tagIds : undefined,
...taxQuery,
};
__unstableMarkNextChangeAsNotPersistent();
setQuery( updateObj );
}
}, [ query.categoryIds, query.tagIds ] );
const onPostTypeChange = ( newValue ) => {
const updateQuery = { postType: newValue };
if ( ! postTypesTaxonomiesMap[ newValue ].includes( 'category' ) ) {
updateQuery.categoryIds = [];
}
if ( ! postTypesTaxonomiesMap[ newValue ].includes( 'post_tag' ) ) {
updateQuery.tagIds = [];
}
// We need to dynamically update the `taxQuery` property,
// by removing any not supported taxonomy from the query.
const supportedTaxonomies = postTypesTaxonomiesMap[ newValue ];
const updatedTaxQuery = Object.entries( taxQuery || {} ).reduce(
( accumulator, [ taxonomySlug, terms ] ) => {
if ( supportedTaxonomies.includes( taxonomySlug ) ) {
accumulator[ taxonomySlug ] = terms;
}
return accumulator;
},
{}
);
updateQuery.taxQuery = !! Object.keys( updatedTaxQuery ).length
? updatedTaxQuery
: undefined;

if ( newValue !== 'post' ) {
updateQuery.sticky = '';
}
setQuery( updateQuery );
};
// Handles categories and tags changes.
const onTermsChange = ( terms, queryProperty ) => ( newTermValues ) => {
const termIds = Array.from(
newTermValues.reduce( ( accumulator, termValue ) => {
const termId = getTermIdByTermValue(
terms.mapByName,
termValue
);
if ( termId ) accumulator.add( termId );
return accumulator;
}, new Set() )
);
setQuery( { [ queryProperty ]: termIds } );
};
const onCategoriesChange = onTermsChange( categories, 'categoryIds' );
const onTagsChange = onTermsChange( tags, 'tagIds' );

const [ querySearch, setQuerySearch ] = useState( query.search );
const onChangeDebounced = useCallback(
debounce( () => {
Expand All @@ -136,42 +107,10 @@ export default function QueryInspectorControls( {
}, 250 ),
[ querySearch, query.search ]
);

useEffect( () => {
onChangeDebounced();
return onChangeDebounced.cancel;
}, [ querySearch, onChangeDebounced ] );

// Returns only the existing term ids (categories/tags) in proper
// format to be used in `FormTokenField`. This prevents the component
// from crashing in the editor, when non existing term ids were provided.
const getExistingTermsFormTokenValue = ( taxonomy ) => {
const termsMapper = {
category: {
queryProp: 'categoryIds',
terms: categories,
},
post_tag: {
queryProp: 'tagIds',
terms: tags,
},
};
const requestedTerm = termsMapper[ taxonomy ];
return ( query[ requestedTerm.queryProp ] || [] ).reduce(
( accumulator, termId ) => {
const term = requestedTerm.terms.mapById[ termId ];
if ( term ) {
accumulator.push( {
id: termId,
value: term.name,
} );
}
return accumulator;
},
[]
);
};

return (
<InspectorControls>
<PanelBody title={ __( 'Settings' ) }>
Expand Down Expand Up @@ -234,26 +173,7 @@ export default function QueryInspectorControls( {
</PanelBody>
{ ! inherit && (
<PanelBody title={ __( 'Filters' ) }>
{ showCategories && categories?.entities?.length > 0 && (
<FormTokenField
label={ __( 'Categories' ) }
value={ getExistingTermsFormTokenValue(
'category'
) }
suggestions={ categories.names }
onChange={ onCategoriesChange }
/>
) }
{ showTags && tags?.entities?.length > 0 && (
<FormTokenField
label={ __( 'Tags' ) }
value={ getExistingTermsFormTokenValue(
'post_tag'
) }
suggestions={ tags.names }
onChange={ onTagsChange }
/>
) }
<TaxonomyControls onChange={ setQuery } query={ query } />
<AuthorControl value={ authorIds } onChange={ setQuery } />
<TextControl
label={ __( 'Keyword' ) }
Expand Down
Loading