Skip to content

Instantly share code, notes, and snippets.

@florianbrinkmann
Last active February 26, 2024 21:40
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save florianbrinkmann/167939b3e0a8c33a5ae3f1c0dc561859 to your computer and use it in GitHub Desktop.
Save florianbrinkmann/167939b3e0a8c33a5ae3f1c0dc561859 to your computer and use it in GitHub Desktop.
Gutenberg FormTokenField block with posts as source
/**
* External dependencies
*/
const { isUndefined, pickBy } = lodash;
/**
* WordPress dependencies
*/
const {
registerBlockType,
} = wp.blocks;
const {
Component,
} = wp.element;
const {
FormTokenField,
} = wp.components;
const {
withSelect,
} = wp.data;
class PostEditComponent extends Component {
constructor() {
super( ...arguments );
}
componentDidMount() {
this.isStillMounted = true;
}
componentWillUnmount() {
this.isStillMounted = false;
}
render() {
const { attributes, setAttributes, posts } = this.props;
const {
selectedPosts,
} = attributes;
let postNames = [];
let postsFieldValue = [];
if ( posts !== null ) {
postNames = posts.map( ( post ) => post.title.raw );
postsFieldValue = selectedPosts.map( ( postId ) => {
let wantedPost = posts.find( ( post ) => {
return post.id === postId;
} );
if ( wantedPost === undefined || ! wantedPost ) {
return false;
}
return wantedPost.title.raw;
} );
}
return(
<div>
<FormTokenField
label='Posts'
value={ postsFieldValue }
suggestions={ postNames }
maxSuggestions={ 20 }
onChange={ ( selectedPosts ) => {
// Build array of selected posts.
let selectedPostsArray = [];
selectedPosts.map(
( postName ) => {
const matchingPost = posts.find( ( post ) => {
return post.title.raw === postName;
} );
if ( matchingPost !== undefined ) {
selectedPostsArray.push( matchingPost.id );
}
}
)
setAttributes( { selectedPosts: selectedPostsArray } );
} }
/>
</div>
)
}
}
registerBlockType( 'slug/postsSelect', {
title: 'Posts',
category: 'layout',
attributes: {
selectedPosts: {
type: 'array',
default: [],
}
},
edit: withSelect( ( select ) => {
const { getEntityRecords } = select( 'core' );
const postsQuery = pickBy( {
per_page: -1,
}, ( value ) => ! isUndefined( value ) );
return {
posts: getEntityRecords( 'postType', 'post', postsQuery ),
};
} )( PostEditComponent ),
save: () => {
return null;
}
} )
@tiadotdev
Copy link

thank you! Super helpful

@SplitterAlex
Copy link

Cheers mate, very helpful!

@perviydesign
Copy link

best

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment