How to create a custom DropdownMenu Button in Gutenberg Paragraph - wordpress

I have some issues developing a Dropdownmenu for Core/Paragraph. I want to add a dropdownmenu to insert text (like Personalized Tags on Email Services).
I'm tried making this code in Vanilla to implement DropdownMenu for Core/Paragraph without success.
My code is:
( function( blocks, element, components, editor ) {
const el = element.createElement;
const { __ } = wp.i18n;
const withSelect = wp.data.withSelect;
const ifCondition = wp.compose.ifCondition;
const compose = wp.compose.compose;
console.log(components);
const EmailTagsMenu = el(
components.Toolbar,
null,
el(
components.DropDownMenu,
{
icon: 'admin-customizer',
isActive: false,
label: __('Insert Tag', 'amauta'),
controls: function(){
return [
{
title: __('Firstname', 'amauta'),
icon: 'admin-customizer',
onClick: function(){
}
},
{
title: __('Lastname', 'amauta'),
icon: 'admin-customizer',
onClick: function(){
}
}
];
}
}
)
);
var EmailTagsButton = compose(
withSelect( function( select ) {
return {
selectedBlock: select( 'core/block-editor' ).getSelectedBlock()
}
} ),
ifCondition( function( props ) {
return (
props.selectedBlock &&
props.selectedBlock.name === 'core/paragraph'
);
} )
)( EmailTagsMenu );
wp.richText.registerFormatType(
'amauta/email_tags', {
title: __('Email Tags', 'amauta' ),
tagName: null,
className: null,
edit: EmailTagsButton,
}
);
}(
window.wp.blocks,
window.wp.element,
window.wp.components,
window.wp.blockEditor
));
Please, can you help me? Thanks!

Related

How would I go about changing the css of the currently selected value

import { HTMLSelect } from '#blueprintjs/core';
let value = '';
const dropdownPanelSelector = () => {
const options = [
{ label: 'Map', value: '' },
{ label: 'Camera', value: 'Camera' },
];
const onChange = (e) => {
console.log(e, e.target.value);
value = e.target.value;
};
return (
<HTMLSelect
className={css.dropdownPanel}
options={options}
selected={value}
onChange={onChange}
/>
);
};
I would like to change the selected box's text and none of the others.
.dropdown select (unsure here){
font-size:2em:
}

Gutenberg Block not saving select option

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

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 I can add a custom control to a page?

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

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

Resources