-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
use-template-part-post.js
52 lines (50 loc) · 1.22 KB
/
use-template-part-post.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
export default function useTemplatePartPost( postId, slug, theme ) {
return useSelect(
( select ) => {
if ( postId ) {
// This is already a custom template part,
// use its CPT post.
return (
select( 'core' ).getEntityRecord(
'postType',
'wp_template_part',
postId
) && postId
);
}
// This is not a custom template part,
// load the auto-draft created from the
// relevant file.
if ( slug && theme ) {
const posts = select( 'core' ).getEntityRecords(
'postType',
'wp_template_part',
{
status: [ 'publish', 'auto-draft' ],
slug,
theme,
}
);
const foundPosts = posts?.filter(
( post ) =>
post.slug === slug &&
post.meta &&
post.meta.theme === theme
);
// A published post might already exist if this template part was customized elsewhere
// or if it's part of a customized template.
const foundPost =
foundPosts?.find( ( post ) => post.status === 'publish' ) ||
foundPosts?.find(
( post ) => post.status === 'auto-draft'
);
return foundPost?.id;
}
},
[ postId, slug, theme ]
);
}