Skip to content

Post Select Button

Matthew Haines-Young edited this page Dec 7, 2021 · 6 revisions

The post select component allows you to have a button (or clickable area) that opens a media-modal like UI for finding and selecting posts. It supports browsing, searching and filtering of posts shown. You can configure it to support different post types, and the number of posts it supports. You can also specify the order of the selected posts.

This functionality is also available as a sidebar control.

image

Usage

image

The components are available globally as window.hm.components Its probably worth creating a reference to make this easier to use.

You can then use this component exactly as you would any other react component.

const { PostSelectButton } = hm.components;
const { attributes, setAttributes } = props;

<PostSelectButton 
    value={ attributes.postIds }
    onSelect={ posts => setAttributes( { postIds: posts.map( p => p.id ) } ) }
    postType="page" 
    btnProps={ { isLarge: true } }
>
    { __( 'Button text' ) }
</PostSelectButton>

Prop Types

  • onSelect Function. Required. Called when the 'select' button is clicked and posts are selected.
  • postType String or Array. Post type. e.g. postType: 'post' or postType: [ 'page', 'post' ]
  • maxPosts Number. Default 1. Maximum number of posts that can be selected.
  • btnProps Object. Optional. Props passed to the Gutenberg core Button component. Refer to the documentation/code for that component for more info on what is supported.
  • termFilters Array. What taxonomy filters are supported in the browse view. If not provided, this defaults to all public taxonomies for this post type, so often not necessary to pass this. e.g. termFilters: [ 'category' ]

Notes

  • The onSelect callback receives full post objects, but the value prop expects ID's only. Whilst these are useful for display puposes, you will probably want to save only the IDs, e.g. setAttributes( { myPosts: posts.map( p => p.id ) } ).
  • By default the button has no appearance. To make your button look like a button, you need to pass the isLarge: true to the buttonProps prop. The default setting (button has no appearance) is useful if you want to make an image or preview of your post clickable.
Clone this wiki locally