Skip to content

Instantly share code, notes, and snippets.

@seothemes
Last active November 20, 2022 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seothemes/334cd132fb5418418a5f54b6b6f811b3 to your computer and use it in GitHub Desktop.
Save seothemes/334cd132fb5418418a5f54b6b6f811b3 to your computer and use it in GitHub Desktop.
Get terms by taxonomy for select control option groups
import { __ } from "@wordpress/i18n";
import { InspectorControls } from "@wordpress/block-editor";
import { SelectControl } from "@wordpress/components";
import { registerBlockType } from "@wordpress/blocks";
import { useSelect } from "@wordpress/data";
import { useState } from "@wordpress/element";
interface selectOption {
value: string,
name: string
}
interface optionGroups {
[label: string]: selectOption[]
}
registerBlockType( 'blockify/taxonomies', {
name: 'blockify/taxonomies',
title: 'Taxonomies',
category: 'blockify',
icon: 'tag',
attributes: {},
edit: ( props: blockProps ) => {
const [ selected, setSelected ] = useState( '' );
const { optionGroups } = useSelect<{ optionGroups: optionGroups }>( ( select ) => {
const taxonomies: Array<{ [key: string]: any }> = select( 'core' ).getTaxonomies( { per_page: -1 } );
const selectOptions: optionGroups = {};
taxonomies?.forEach( taxonomy => {
const terms: Array<{ [key: string]: string }> = select( 'core' ).getEntityRecords( 'taxonomy', taxonomy.slug, { per_page: -1 } );
terms?.forEach( term => {
if ( ! selectOptions[taxonomy.name] ) {
selectOptions[taxonomy.name] = [];
}
selectOptions[taxonomy.name].push( {
value: term.id,
name: term.name
} );
} );
} );
return {
optionGroups: selectOptions
}
} ) ?? {};
return <>
<div>
{ selected ?? __( 'Select taxonomy' ) }
</div>
<InspectorControls>
<SelectControl
label={ __( 'Select taxonomy', 'blockify' ) }
value={ selected }
onChange={ ( selection ) => {
setSelected( selection )
} }
>
{ Object?.keys( optionGroups ?? {} )?.map( group => (
<optgroup label={ group }>
{ optionGroups[group].map( ( option: selectOption ) => (
<option value={ option.value }>{ option.name }</option>
) ) }
</optgroup>
) ) }
</SelectControl>
</InspectorControls>
</>;
},
save: ( props ) => {
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment