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

Template for specific category: only load posts from that category in post template block #43699

Merged
merged 3 commits into from
Sep 7, 2022
Merged
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
20 changes: 19 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,11 @@ export default function PostTemplateEdit( {
const [ { page } ] = queryContext;
const [ activeBlockContextId, setActiveBlockContextId ] = useState();

const { records: categories } = useEntityRecords( 'taxonomy', 'category', {
oandregal marked this conversation as resolved.
Show resolved Hide resolved
context: 'view',
per_page: -1,
} );

const { posts, blocks } = useSelect(
( select ) => {
const { getEntityRecords, getTaxonomies } = select( coreStore );
Expand Down Expand Up @@ -155,6 +160,18 @@ export default function PostTemplateEdit( {
if ( templateSlug?.startsWith( 'archive-' ) ) {
query.postType = templateSlug.replace( 'archive-', '' );
postType = query.postType;
} else if (
templateSlug?.startsWith( 'category-' ) &&
!! categories
) {
const targetSlug = templateSlug.replace( 'category-', '' );
const categoryIds = categories
?.filter( ( { slug } ) => slug === targetSlug )
.map( ( { id } ) => id );
query.taxQuery = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is useful, though we need to make it so any taxonomy works by default. I'm thinking on tags but also any 3rd party taxonomies (e.g.: product categories that Woo uses, etc).

category: categoryIds,
};
taxQuery = query.taxQuery;
}
}
// When we preview Query Loop blocks we should prefer the current
Expand Down Expand Up @@ -182,6 +199,7 @@ export default function PostTemplateEdit( {
taxQuery,
parents,
previewPostType,
categories,
]
);
const blockContexts = useMemo(
Expand Down