Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Last active November 20, 2025 10:18
Show Gist options
  • Select an option

  • Save juanmaguitar/0a4f8afb59252cf79d942f5cfce8b787 to your computer and use it in GitHub Desktop.

Select an option

Save juanmaguitar/0a4f8afb59252cf79d942f5cfce8b787 to your computer and use it in GitHub Desktop.
// Helper: wait for all records of a given post type.
const getTypes = async ( types ) => {
return await Promise.all(
types.map(
( type ) =>
new Promise( ( resolve ) => {
const unsub = wp.data.subscribe( () => {
const items = wp.data
.select( 'core' )
.getEntityRecords( 'postType', type );
if ( items ) {
unsub();
resolve( { type, items } );
}
} );
} )
)
);
};
// Helper: wait until all post types are available.
const getAllPostTypes = () => {
return new Promise( ( resolve ) => {
const unsub = wp.data.subscribe( () => {
const postTypes = wp.data
.select( 'core' )
.getEntityRecords( 'root', 'postType' );
if ( postTypes ) {
unsub();
resolve( postTypes.map( ( { slug } ) => slug ) );
}
} );
} );
};
// Combine both: first get all post types, then their entities.
const getAllTypesWithEntities = async () => {
const types = await getAllPostTypes();
const results = await getTypes( types );
results.forEach( ( { type, items } ) => {
console.log( `Fetched ${ items.length } records for ${ type }` );
} );
};
// Run it
getAllTypesWithEntities();
const getTypes = async (types) => await Promise.all(types.map(type =>
new Promise(resolve => {
const unsub = wp.data.subscribe(() => {
const items = wp.data.select('core').getEntityRecords('postType', type);
items && (unsub(), resolve({ type, items }));
});
})
));
// Use it
(await getTypes(['post','page'])).forEach(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment