Last active
November 20, 2022 00:30
-
-
Save seothemes/334cd132fb5418418a5f54b6b6f811b3 to your computer and use it in GitHub Desktop.
Get terms by taxonomy for select control option groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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