Skip to content

Instantly share code, notes, and snippets.

@psorensen
Last active December 1, 2021 16:40
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 psorensen/a4c6267d8e89ad6ae741e1f30afae69c to your computer and use it in GitHub Desktop.
Save psorensen/a4c6267d8e89ad6ae741e1f30afae69c to your computer and use it in GitHub Desktop.
Extending query block to support custom taxonomies
import { TopicPicker } from './topic-picker';
const { createHigherOrderComponent } = wp.compose;
const { InspectorControls } = wp.blockEditor;
const { PanelBody, PanelRow } = wp.components;
const { addFilter } = wp.hooks;
const { __ } = wp.i18n;
const enableOnBlocks = ['core/query'];
const queryLoopSettings = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { name, setAttributes } = props;
// If not on enabled blocks abandon
if (!enableOnBlocks.includes(name)) {
return <BlockEdit {...props} />;
}
const onHandleChange = (term) => {
const {
attributes: { query },
} = props;
const newQuery = {};
newQuery.search = JSON.stringify({
tax_query: [
{
taxonomy: 'sf_topic',
terms: [parseInt(term, 10)],
},
],
});
const updatedQuery = Object.assign(query, newQuery);
setAttributes({ query: updatedQuery });
};
return (
<>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody title={__('More Settings', 'newsroom')}>
<PanelRow>
<TopicPicker onChange={(term) => onHandleChange(term)} />
</PanelRow>
</PanelBody>
</InspectorControls>
</>
);
};
});
addFilter('editor.BlockEdit', 'newsroom/query-loop-settings', queryLoopSettings);
/**
* Image Block Modal Toggle
* - adds toggle to enable or disable image modal
*/
const { SelectControl } = wp.components;
const { useSelect } = wp.data;
const { __ } = wp.i18n;
export const TopicPicker = ({ onChange }) => {
let topics = useSelect((select) =>
select('core').getEntityRecords('taxonomy', 'sf_topic', { per_page: 30 }),
);
let options = [
{
name: 'Loading',
id: '',
},
];
if (topics && topics.length) {
const defaultTopic = {
name: __('Select a Topic', 'newsroom'),
id: '',
};
topics = [defaultTopic, ...topics];
}
const topicOptions =
topics &&
topics.map(({ id, name }) => {
return {
value: id,
label: name,
};
});
if (topicOptions) {
options = topicOptions;
}
return (
<SelectControl
label={__('Select a Topic', 'newsroom')}
options={options}
onChange={(term) => onChange(term)}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment