I have a block that renders titles of all existing posts in the <Modal/>. I retrieve it from the server using <ServerSideRender/> (that returns plain html). I want to be able to choose one of the titles (ideally save it in the postTitle attribute) and display it in the block.
attributes: {
postTitle: {
type: 'string'
}
},
edit(props) {
const { attributes } = props;
const { postTitle } = props.attributes;
const MyModal = withState( {
isOpen: false,
} )
( ( { isOpen, setState } ) => (
<div>
<Button isDefault onClick={ () => setState( { isOpen: true } ) }>Choose</Button>
{ isOpen ?
<Modal onRequestClose={ () => setState( { isOpen: false } ) }>
<ServerSideRender
block="my-blocks/wordpress-title"
attributes={attributes}
/>
</Modal>
: null }
</div>
) );
return ([
<InspectorControls>
<div>
<strong>Choose Wordpress title:</strong>
<MyModal/>
</div>
</InspectorControls>,
]);
},
Is there any sensible way to retrieve data from a server, so it was possible to operate on it within a block?
Related
I am working on creating a Gutenberg block that will have a dropdown of posts and the user will pick one.
It saves the selection, but if I refresh the page the selection is not there anymore, switches back to 'ALL'.
It also displays fine in the front end, however, if I try to edit the page, the selections are gone and the dropdown switch back to all.
Any ideas on this one?
const { RichText, InspectorControls, ColorPalette, MediaUpload } = wp.blockEditor;
const { PanelBody, IconButton, RangeControl, TextControl, SelectControl } = wp.components;
wp.data.select('core').getEntityRecords('postType', 'beers');
registerBlockType('tg/product-block', {
title: 'TG Product Block',
description: 'Showcasing Products in a block',
parent: ['tg/products-block'],
atrributes: {
beerName: {
type:'string'
},
beerId: {
type:'string'
}
},
edit: ({attributes, setAttributes}) => {
const {
beerName,
beerId,
} = attributes;
function getBeers() {
let options = [{ value: 0, label: 'All' }];
let beers = wp.data.select('core').getEntityRecords('postType', 'beers');
beers.forEach((beer) => {
options.push({ value: beer.id, label: beer.title.rendered });
});
return options;
}
function onDropdownChangeOne (newBeerId) {
console.log('newBeerId', newBeerId)
setAttributes({ beerId: newBeerId })
fetch(window.location.protocol + '//' + window.location.hostname + ':10016/wp-json/wp/v2/beers/' + newBeerId)
.then(response => response.json())
.then(data => {
console.log(data)
setAttributes({beerName: data.title.rendered})
})
}
return([
<InspectorControls style={{ marginBottom: '40px' }}>
<PanelBody title={'Choose Category For The First Box'}>
</PanelBody>
</InspectorControls>,
<div className="col-md-4">
<SelectControl
value={beerId}
label={'Select a Post'}
options={getBeers()}
onChange={onDropdownChangeOne}
/>
<RichText.Content tagName="h2"
value={beerName}
/>
</div>
])
},
save: ({attributes}) => {
const {
beerName,
beerId,
} = attributes;
return(
<div className="col-md-4">
<RichText.Content tagName="h2"
value={beerName}
/>
</div>
)
}
})```
I have been tasked with preventing addFilter() from running on certain custom post types using the new Gutenberg API and not any WP PHP. It's currently fed into the editor.PostFeaturedImage hook, meaning it fires every time the Gutenberg editor loads the Featured Image box.
The Filter calls a function that adds a dropdown menu underneath the featured image box to allow users to pick a contributor (which are themselves custom post types) to credit the image to.
The filter should not run on the contributor custom post type, but should run on other custom post types. There should still be a featured image box for the contributor custom post type, but no dropdown.
Letting the hook fire and then canceling within the function works but the function itself is resource heavy and the directive is to prevent the function from firing at all. The idea being that the built-in hook/function would fire instead.
Borrowing from this ticket, I attempted to place the main function setFeaturedImageArtist within an anonymous function that also printed the post type to console in addFilter(). I was able to get the post type to print, but calling setFeaturedImageArtist function didn't work as expected.
wp.hooks.addFilter( 'editor.PostFeaturedImage', 'blocks/featured-image-artist', function() {
console.log(wp.data.select("core/editor").getCurrentPostType())
return setFeaturedImageArtist()
});
Placing setFeaturedImageArtistin a wrapper function like so didn't work either. I'm assuming it's because it's the same thing.
function checkPostType() {
console.log(wp.data.select("core/editor").getCurrentPostType())
return setFeaturedImageArtist()
}
wp.hooks.addFilter( 'editor.PostFeaturedImage', 'blocks/featured-image-artist', checkPostType);
Here is the component the filter is triggering:
function setFeaturedImageArtist( OriginalComponent ) {
return ( props ) => {
const artistSelect = compose.compose(
withDispatch( function( dispatch, props ) {
return {
setMetaValue: function( metaValue ) {
dispatch( 'core/editor' ).editPost(
{ meta: { 'featured-image-artist': metaValue } }
);
}
}
} ),
withSelect( function( select, props ) {
let query = {
per_page : 20,
metaKey : '_author_type',
metaValue : 'artist'
};
let postType = select("core/editor").getCurrentPostType();
if ( postType === 'contributor' ) {
return null
}
// Please see below
// if ( postType === 'contributor' ) {
// return {
// postType
// }
// }
return {
posts: select( 'core' ).getEntityRecords( 'postType', 'contributor', query ),
metaValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'featured-image-artist' ],
}
} ) )( function( props ) {
var options = [];
// This works in removing the dropdown for authors/artists
// if (props.postType === 'contributor'){
// return null
// }
if( props.posts ) {
options.push( { value: 0, label: __( 'Select an artist', 'blocks' ) } );
props.posts.forEach((post) => {
options.push({value:post.id, label:post.title.rendered});
});
} else {
options.push( { value: 0, label: __( 'Loading artists...', 'blocks' ) } )
}
return el( SelectControl,
{
label: __( 'Art Credit:', 'blocks' ),
options : options,
onChange: ( content ) => {
props.setMetaValue( content );
},
value: props.metaValue,
}
);
}
);
return (
el( 'div', { }, [
el( OriginalComponent, props ),
el( artistSelect )
] )
);
}
}
wp.hooks.addFilter( 'editor.PostFeaturedImage', 'blocks/featured-image-artist', setFeaturedImageArtist );
Here is the redacted component the filter is triggering:
function setFeaturedImageArtist( OriginalComponent ) {
return ( props ) => {
const artistSelect = compose.compose(
...
)( function( props ) {
... // Cancelling out here works, but resources are loaded by this point.
});
return (
el( 'div', { }, [
el( OriginalComponent, props ),
el( artistSelect )
])
);
}
}
wp.hooks.addFilter( 'editor.PostFeaturedImage', 'blocks/featured-image-artist', setFeaturedImageArtist );
This is the React error being received:
Element type is invalid: expected a string (for built-in components) or
a class/function (for composite components) but got: undefined.
I'm not sure what the best approach to this would be, and the documentation is scant/barely applicable. Is creating a custom hook that mimics editor.PostFeaturedImage but only fires on certain custom post types a possibility? Or is there some way to call a function like setFeaturedImageArtist within a wrapper that checks the post type?
Wordpress Hooks on Github
Hooks in Wordpress Handbook
I tried to recreate the script and fixed some issues:
const { createElement: el } = wp.element;
const { compose } = wp.compose;
const { withSelect, withDispatch } = wp.data;
const { SelectControl } = wp.components;
const { __ } = wp.i18n;
const ArtistSelect = compose(
withDispatch(function(dispatch, props) {
return {
setMetaValue: function(metaValue) {
dispatch("core/editor").editPost({
meta: { "featured-image-artist": metaValue }
});
}
};
}),
withSelect(function(select, props) {
let query = {
per_page: 20,
metaKey: "_author_type",
metaValue: "artist"
};
return {
postType: select("core/editor").getCurrentPostType(),
posts: select("core").getEntityRecords("postType", "contributor", query),
metaValue: select("core/editor").getEditedPostAttribute("meta")[
"featured-image-artist"
]
};
})
)(function(props) {
var options = [];
// This works in removing the dropdown for authors/artists
if (props.postType === "contributor") {
return null;
}
if (props.posts) {
options.push({ value: 0, label: __("Select an artist", "blocks") });
props.posts.forEach(post => {
options.push({ value: post.id, label: post.title.rendered });
});
} else {
options.push({ value: 0, label: __("Loading artists...", "blocks") });
}
return el(SelectControl, {
label: __("Art Credit:", "blocks"),
options: options,
onChange: content => {
props.setMetaValue(content);
},
value: props.metaValue
});
});
function setFeaturedImageArtist(OriginalComponent) {
return props => {
return el("div", {}, [el(OriginalComponent, props), el(ArtistSelect)]);
};
}
wp.hooks.addFilter(
"editor.PostFeaturedImage",
"blocks/featured-image-artist",
setFeaturedImageArtist
);
ArtistSelect is a component so we take it outside of setFeaturedImageArtist function. withSelect had a check for the postType that made it return null. Instead of that we pass that variable and then return null in the components render. An alternative would be to check inside setFeaturedImageArtist. This is a fixed version using JSX. Hope its clear:
const { compose } = wp.compose;
const { withSelect, withDispatch, select } = wp.data;
const { SelectControl } = wp.components;
const { __ } = wp.i18n;
const { addFilter } = wp.hooks;
const ArtistSelect = compose(
withDispatch(dispatch => {
return {
setMetaValue: metaValue => {
dispatch("core/editor").editPost({
meta: { "featured-image-artist": metaValue }
});
}
};
}),
withSelect(select => {
const query = {
per_page: 20,
metaKey: "_author_type",
metaValue: "artist"
};
return {
posts: select("core").getEntityRecords("postType", "contributor", query),
metaValue: select("core/editor").getEditedPostAttribute("meta")[
"featured-image-artist"
]
};
})
)(props => {
const { posts, setMetaValue, metaValue } = props;
const options = [];
if (posts) {
options.push({ value: 0, label: __("Select an artist", "blocks") });
posts.forEach(post => {
options.push({ value: post.id, label: post.title.rendered });
});
} else {
options.push({ value: 0, label: __("Loading artists...", "blocks") });
}
return (
<SelectControl
label={__("Art Credit:", "blocks")}
options={options}
onChange={content => setMetaValue(content)}
value={metaValue}
/>
);
});
const setFeaturedImageArtist = OriginalComponent => {
return props => {
const post_type = select("core/editor").getCurrentPostType();
if (post_type === "contributor") {
return <OriginalComponent {...props} />;
}
return (
<div>
<OriginalComponent {...props} />
<ArtistSelect />
</div>
);
};
};
wp.hooks.addFilter(
"editor.PostFeaturedImage",
"blocks/featured-image-artist",
setFeaturedImageArtist
);
I need to add a checkbox to the page editing form in Gutenberg without third-party plugins like ACF. I did some tutorials, including the one on the official Wordpress page, but it does not behave as I need to.
I already have the addition to the sidebar (I replaced the checkbox with a toogle but it would be the same), the element does not work itself, if I click does not change its status, nor can I store the value when saving the page.
Formerly I would have solved it with metabox, but it is no longer compatible with this version of Wordpress.
What should I modify in the code for the component to change its status and then store it in database when saving a page?
I tried with this and works, but isn't what I need: https://developer.wordpress.org/block-editor/tutorials/plugin-sidebar-0/plugin-sidebar-1-up-and-running/
I tried whit this: https://www.codeinwp.com/blog/make-plugin-compatible-with-gutenberg-sidebar-api/
export class MyPluginSidebar{
constructor(wp){
const { __ } = wp.i18n;
const {
PluginSidebar,
PluginSidebarMoreMenuItem
} = wp.editPost;
const {
PanelBody,
TextControl,
ToggleControl
} = wp.components;
const {
Component,
Fragment
} = wp.element;
const { withSelect } = wp.data;
const { registerPlugin } = wp.plugins;
const { withState } = wp.compose;
class Hello_Gutenberg extends Component {
constructor() {
super( ...arguments );
this.state = {
key: '_hello_gutenberg_field',
value: '',
}
wp.apiFetch( { path: `/wp/v2/posts/${this.props.postId}`, method: 'GET' } ).then(
( data ) => {
console.log('apiFetch data', data.meta);
this.setState( {
value: data.meta._hello_gutenberg_field
} );
return data;
},
( err ) => {
console.log('wp api fetch error', err);
return err;
}
);
}
static getDerivedStateFromProps( nextProps, state ) {
if ( ( nextProps.isPublishing || nextProps.isSaving ) && !nextProps.isAutoSaving ) {
wp.apiRequest( { path: `/hello-gutenberg/v1/update-meta?id=${nextProps.postId}`, method: 'POST', data: state } ).then(
( data ) => {
return data;
},
( err ) => {
return err;
}
);
}
}
render() {
var hasFixedBackground = true;
return (
<Fragment>
<PluginSidebarMoreMenuItem
target="hello-gutenberg-sidebar"
>
{ __( 'Sidebar title' ) }
</PluginSidebarMoreMenuItem>
<PluginSidebar
name="hello-gutenberg-sidebar"
title={ __( 'Sidebar title' ) }
>
<PanelBody>
<ToggleControl
label="Control label"
//help={ hasFixedBackground ? 'Has fixed background.' : 'No fixed background.' }
checked={ hasFixedBackground }
//onChange={ () => this.setState( ( state ) => ( { hasFixedBackground: ! state.hasFixedBackground } ) ) }
/>
</PanelBody>
</PluginSidebar>
</Fragment>
)
}
}
// Pass post ID to plugin class
// Prevent to save on each state change, just save on post save
const HOC = withSelect( ( select, { forceIsSaving } ) => {
const {
getCurrentPostId,
isSavingPost,
isPublishingPost,
isAutosavingPost,
} = select( 'core/editor' );
return {
postId: getCurrentPostId(),
isSaving: forceIsSaving || isSavingPost(),
isAutoSaving: isAutosavingPost(),
isPublishing: isPublishingPost(),
};
} )( Hello_Gutenberg );
registerPlugin( 'hello-gutenberg', {
icon: 'admin-site',
render: HOC,
} );
}
}
This code register the sidebar, add the control but didn't change his state neither save in database.
Any help are welcome.
Regards!
If you want to save data that you have added later on you gutenberg block you need to use addFilter. I can show you an example i am using:
wp.hooks.addFilter('blocks.registerBlockType', 'custom/filter', function(x,y) {
if(x.hasOwnProperty('attributes')){
x.attributes.background_image = {
type: 'string',
default: ''
};
}
return x;
});
I have been trying to create a Gutenberg block that displays a list of categories as checkboxes on my WordPress edit pages, and then displays on the frontend page a list of posts that are linked to the selected categories.
I have successfully added the checkboxes for the edit pages. When I choose the categories, update, then refresh the page, they stay the way I previously left them.
But I can't seem to figure out how I can do an API call to get a list of posts linked to the categories I've selected.
This is my edit code and attributes:
let globalCategories = [];
let globalPosts = [];
const data = wp.apiFetch({ path: '/wp/v2/categories' })
.then(( obj ) => {
globalCategories.push(obj.map(o => {
return o;
}));
return globalCategories;
});
registerBlockType( 'mdlr/multi-category-list', {
title: __( 'Digiminster: Multi Category List' ),
icon: 'lock',
category: 'common',
attributes: {
checkedArray: { type: 'array' },
postsArray: { type: 'array' }
},
edit(props) {
console.log("checkedArray: ", props.attributes.checkedArray);
if(props.attributes.checkedArray === undefined) {
props.attributes.checkedArray = globalCategories[0];
}
function updateContent(event, index) {
props.setAttributes({
checkedArray: props.attributes.checkedArray.map((o, i) => {
if (index === i) {
o.checked = event.target.checked;
}
return o;
})
});
}
return props.attributes.checkedArray.map((c, i) => (
<div>
<input
type="checkbox"
checked={c.checked}
onChange={e => updateContent(e, i)}
/>
<label>{c.name}</label>
</div>
));
},
...
And this is my save code:
save: class extends wp.element.Component {
constructor(props) {
super(props);
this.state = props.attributes;
}
updateContent(contentData) {
console.log("Hello", globalPosts);
this.setState({ postsArray: globalPosts });
console.log(this.state.postsArray); // <- Returns undefined
}
render() {
let checkedArray = this.state.checkedArray;
if (checkedArray !== undefined) {
let categoryIds = checkedArray.filter(c => c.checked === true).map(c => c.id).join();
if (categoryIds !== '') {
wp.apiFetch({ path: '/wp/v2/posts?categories=' + categoryIds })
.then(( obj ) => {
globalPosts = obj.map(o => o);
console.log("Global posts", globalPosts);
return globalPosts;
});
}
}
let postsLoadingTimer = setInterval(() => {
if (globalPosts !== undefined) {
this.updateContent(globalPosts);
clearInterval(postsLoadingTimer);
}
});
return (
<div>helloooooo</div>
);
}
}
I want to be able to get the this.state.postsArray, loop through it and display my posts but this.setState doesn't seem to be working and is making this.state.postsArray return 'undefined'.
I've written the timer thinking that it might help me update the content with this.setState.
My main goal is to display a list of posts based on selected categories.
As shown in the code snippet below, I am trying to append HTML or JSX to RichText content in vain.
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;
registerBlockType( /* ... */, {
// ...
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
default: [],
},
},
edit( { className, attributes, setAttributes } ) {
const updateContentWithString = ( content ) => {
setAttributes( { content: content.concat( 'test' ) } );
}
const updateContentWithHTML = ( content ) => {
setAttributes( { content: content.concat( <Button isDefault >Test Button</Button> ) } );
}
return (
<RichText
tagName="p"
className={ className }
value={ attributes.content }
onChange={ updateContentWithString } // updateContentWithString works fine BUT updateContentWithHTML doesn't work at all
/>
);
},
save( { attributes } ) {
return <RichText.Content tagName="p" value={ attributes.content } />;
}
} );
I am wondering why updateContentWithString() works fine BUT updateContentWithHTML() doesn't work at all.
Kindly guide me on this.
Thanks
Try
setAttributes( { content: content.concat( '<Button isDefault >Test Button</Button> )' } );
In JSX <Button/> will be preprocessed/conversed to React.createElement to create component.
Note: In JSX <Button/> differs from <button/> (component vs. html)
UPDATE:
Above was related to react/JSX only.
I don't know or used Gutenberg (yet) but according to this html elements should be passed as objects, not html source. Probably you should use wp.element.createElement or RichText or even define/use own custom block types.
Search for method of editing/updating/creating html (elements) in Gutenberg.