Skip to content

Instantly share code, notes, and snippets.

@GarrettWeinberg
Last active March 6, 2020 14:22
Show Gist options
  • Save GarrettWeinberg/d7ce7c6353330e8f38b2848e9d5679bd to your computer and use it in GitHub Desktop.
Save GarrettWeinberg/d7ce7c6353330e8f38b2848e9d5679bd to your computer and use it in GitHub Desktop.
latest posts block
import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { InspectorControls } from "@wordpress/block-editor";
import { PanelBody, SelectControl } from "@wordpress/components";
registerBlockType( 'create-block/better-latest-posts', {
title: __( 'Better Latest Posts', 'create-block' ),
description: __(
'Example block written with ESNext standard and JSX support – build step required.',
'create-block'
),
category: 'widgets',
icon: 'smiley',
supports: {
align: true,
html: false,
},
attributes: {
categories: {
type: 'object'
},
selectedCategory: {
type: 'string'
},
postsPerPage: {
type: 'string',
},
},
edit(props) {
if( ! props.attributes.categories) {
wp.apiFetch( { path: '/wp/v2/categories' } ).then(
categories => {
props.setAttributes( {
categories: categories
})
}
)
}
if( ! props.attributes.categories ){
return 'loading...';
}
if ( props.attributes.categories && props.attributes.categories === 0){
return 'No Categories Found';
}
console.log(props.attributes.categories);
return (
<InspectorControls>
<PanelBody title="Post Configuration" icon="" initialOpen={true}>
<SelectControl
label="Post Category"
help="Select which post category will be displayed"
value={props.attributes.selectedCategory}
options={props.attributes.categories.map( category => {category.name})}
onChange={value => {
props.setAttributes({ selectedCategory: value });
}}
/>
<SelectControl
label="Posts To Show"
help="Select how many posts will be displayed"
value={props.attributes.postsPerPage}
options={[
{ label: "1", value: "1" },
{ label: "2", value: "2" },
{ label: "3", value: "3" },
{ label: "4", value: "4" },
{ label: "5", value: "5" }
]}
onChange={value => {
props.setAttributes({ postsPerPage: value });
}}
/>
</PanelBody>
</InspectorControls>
);
},
/**
* The save function defines the way in which the different attributes should be combined
* into the final markup, which is then serialized by the block editor into `post_content`.
*
* @see https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/#save
*
* @return {WPElement} Element to render.
*/
save() {
return null;
},
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment