How I can add a custom control to a page? - wordpress

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;
});

Related

Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined

I'm developing a blog using nextJS & sanity. And I connected sanity with nextJS and it's perfectly working in development mode. But when I try to deploy in Vercel or build through the VSCode, it shows the below error.
info - Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined.
Here is my component overview
export default function SinglePost({ post }) {
const {
title,
imageUrl,
publishedAt,
description,
topics,
rescources,
sourcecode,
body = [],
} = post;
return(
<div>
<h1>{title}</h1>
//remaining code....
</div>)
}
const query = groq`*[_type == "post" && slug.current == $slug][0]{
"title": title,
"imageUrl": mainImage.asset->url,
description,
"topics": topics[],
"rescources": rescources[],
"sourcecode": sourcecode,
"publishedAt": publishedAt,
body,
}`;
export async function getStaticPaths() {
const paths = await client.fetch(
`*[_type == "post" && defined(slug.current)][].slug.current`
);
return {
paths: paths.map((slug) => ({ params: { slug } })),
fallback: true,
};
}
export async function getStaticProps(context) {
const { slug = "" } = context.params;
const post = await client.fetch(query, { slug });
return {
props: {
post,
},
};
}
Hi i found this to work
const Page: NextPage = (props: any) => {
const { post = undefined || {} } = props
const { title = "Undefined title" } = post
return (
<>
<Head>
<title>{title}</title>
</Head>
</>
)
}
const query = groq`*[_type == "post" && slug.current == $slug][0]{
title,
"name": author->name,
"authorImage": author->image,
"categories": categories[]->title,
}`
export async function getStaticProps(context: any) {
// It's important to default the slug so that it doesn't return "undefined"
const { slug = '' } = context.params
const post = await client.fetch(query, { slug })
return {
props: {
post,
},
}
}
I was able to solve this problem.
Solution: Without destructuring 'title', I got a value through the direct access
<h1>{post.title}</h1>
i got the same issue, the error says prerender-error , I add a if block to handle the fallback :
const PostId = ({postId}) => {
const router = useRouter()
if (router.isFallback) {
return <div>Loading...</div>
}
return (
...
)
...
}
and it builds successfully, make sure you handle the fallback in page

Prevent wp.hooks.addFilter() from Running on Certain Custom Post Types in Gutenberg

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
);

How can I render my posts with my custom WordPress Gutenberg block by category?

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.

Gutenberg Wordpress: Extending Core Block

I am trying to add a padding Inspector Control to all core block of the new Gutenberg Wordpress Editor. I have created the Control on the Editor and now I am trying to apply this style to the block element its self.
But I keep getting This block contains unexpected or invalid content. Error on the blocks. Can anyone help me out here on what exactly I am not doing?
var paddingEditor = wp.compose.createHigherOrderComponent(function(
BlockEdit
) {
return function(props) {
var padding = props.attributes.padding || 0;
handleChange = name => newValue => {
if (props) {
props.setAttributes({ [name]: newValue });
}
};
return el(
Fragment,
{},
el(BlockEdit, props),
el(
editor.InspectorControls,
{},
el(
components.PanelBody,
{
title: "Padding",
className: "",
initialOpen: false
},
el("p", {}, "Padding"),
el(components.TextControl, {
value: padding,
onChange: this.handleChange("padding")
})
)
)
);
};
},
"paddingStyle");
wp.hooks.addFilter(
"editor.BlockEdit",
"my-plugin/padding-style",
paddingStyle
);
function AddPaddingAttribute(element, blockType, attributes) {
Object.assign(blockType.attributes, {
padding: {
type: "string"
}
});
return element;
}
wp.hooks.addFilter(
"blocks.getSaveElement",
"my-plugin/add-padding-attr",
AddPaddingAttribute
);
function AddPaddingStyle(props, blockType, attributes) {
if (attributes.padding) {
props.style = lodash.assign(props.style, { padding: attributes.padding });
}
return props;
}
wp.hooks.addFilter(
"blocks.getSaveContent.extraProps",
"my-plugin/add-background-color-style",
AddPaddingStyle
);
PHP
function register_block_extensions(){
wp_register_script(
'extend-blocks', // Handle.
get_template_directory_uri() . '/js/extend-blocks.js',
array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-editor' )
);
wp_enqueue_script( 'extend-blocks' );
}
add_action('enqueue_block_editor_assets', 'register_block_extensions');
Your editor.BlockEdit looks right, but it's hard for me to parse the older syntax. Assuming it is correct, you'll need to replace blocks.getSaveElement with this:
function AddPaddingAttribute(props) {
if (props.attributes) { // Some modules don't have attributes
props.attributes = Object.assign(
props.attributes,
{
padding: {}
}
);
}
return props;
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'my-plugin/add-padding-attr',
AddPaddingAttribute
);
And modify blocks.getSaveContent.extraProps to this:
function AddPaddingStyle(props, blockType, attributes) {
return Object.assign(
props,
{
style: {
padding: attributes.padding
}
}
);
}
wp.hooks.addFilter(
"blocks.getSaveContent.extraProps",
"my-plugin/add-background-color-style",
AddPaddingStyle
);

Gutenberg blocks - processing server data within a block

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?

Resources