Skip to content

Commit

Permalink
Template for specific category: only load posts from that category in…
Browse files Browse the repository at this point in the history
… post template block (#43699)
  • Loading branch information
oandregal authored Sep 7, 2022
1 parent c1cf175 commit f17f113
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion packages/block-library/src/post-template/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
store as blockEditorStore,
} from '@wordpress/block-editor';
import { Spinner } from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { store as coreStore, useEntityRecords } from '@wordpress/core-data';

const TEMPLATE = [
[ 'core/post-title' ],
Expand Down Expand Up @@ -95,6 +95,18 @@ export default function PostTemplateEdit( {
const [ { page } ] = queryContext;
const [ activeBlockContextId, setActiveBlockContextId ] = useState();

let categorySlug = null;
if ( templateSlug?.startsWith( 'category-' ) ) {
categorySlug = templateSlug.replace( 'category-', '' );
}
const { records: categories, hasResolved: hasResolvedCategories } =
useEntityRecords( 'taxonomy', 'category', {
context: 'view',
per_page: -1,
_fields: [ 'id' ],
slug: categorySlug,
} );

const { posts, blocks } = useSelect(
( select ) => {
const { getEntityRecords, getTaxonomies } = select( coreStore );
Expand Down Expand Up @@ -155,6 +167,11 @@ export default function PostTemplateEdit( {
if ( templateSlug?.startsWith( 'archive-' ) ) {
query.postType = templateSlug.replace( 'archive-', '' );
postType = query.postType;
} else if ( !! categorySlug && hasResolvedCategories ) {
query.taxQuery = {
category: categories.map( ( { id } ) => id ),
};
taxQuery = query.taxQuery;
}
}
// When we preview Query Loop blocks we should prefer the current
Expand Down Expand Up @@ -182,6 +199,9 @@ export default function PostTemplateEdit( {
taxQuery,
parents,
previewPostType,
categories,
categorySlug,
hasResolvedCategories,
]
);
const blockContexts = useMemo(
Expand Down

0 comments on commit f17f113

Please sign in to comment.