skip to Main Content

I’m trying to add extra toggle button to core gutenberg blocks and all are working fine except widget blocks and specially rss block.

  • Added one button
  • on button click add new attribute
  • that attribute is not saving and block crashes

Here is the render API path:

domain.com/wp-json/wp/v2/block-renderer/core/rss?context=edit&attributes%5Bcolumns%5D=2&attributes%5BblockLayout%5D=list&attributes%5BfeedURL%5D=https%3A%2F%domain.com%2Fblog%2F&attributes%5BitemsToShow%5D=5&attributes%5BdisplayExcerpt%5D=false&attributes%5BdisplayAuthor%5D=false&attributes%5BdisplayDate%5D=false&attributes%5BexcerptLength%5D=55&attributes%5Bdatatext%5D=el1683204085047&post_id=2&_locale=user

It shows 400 Bad request and if you check that Rest API URL there is datatext attribute which is custom attribute I’m trying to add.

Error: react.js?ver=18.2.0:1120 Uncaught Error: Objects are not valid as a React child (found: object with keys {error, errorMsg}). If you meant to render a collection of children, use an array instead.

Please suggest me the best way to add extra attribute to core/rss wordpress block.

2

Answers


  1. I replicated your error in WP 6.2 on the core/rss block. Extending the block with a new attribute via the filter blocks.registerBlockType followed by editing then saving worked until a feedURL was added.

    As the RSS block uses server side rendering, I reviewed the render_callback code as the ServerSideRender error read: Error loading block: Invalid parameter(s): attributes after adding feedURL, eg:

    No error

    <!-- wp:rss {"datatext":"test"} /-->
    

    Error

    <!-- wp:rss {"feedURL":"https://stackoverflow.com/feeds/tag?tagnames=wordpress-gutenberg\u0026sort=newest","datatext":"test"} /-->
    

    As the RSS block is rendered using PHP, I would suggest a way around the issue to be creating a block variation and changing the render callback of your variation. Create your own PHP function that mirrors the default RSS render callback and also handles your extra parameter which should avoid the Invalid parameter(s) error.

    For completeness, below is the code I tested adding the extra attribute with:

    JS

    import { InspectorControls } from '@wordpress/block-editor';
    import { PanelBody, TextControl } from '@wordpress/components';
    import { createHigherOrderComponent } from '@wordpress/compose';
    import { addFilter } from '@wordpress/hooks';
    
    
    function addDatatextAttribute(settings, name) {
        if (name !== 'core/rss') {
            return settings;
        }
    
        return lodash.assign({}, settings, {
            attributes: lodash.assign({}, settings.attributes, {
                datatext: {
                    type: 'string',
                    default: 'test'  
                }
            }),
        })
    }
    
    addFilter(
        'blocks.registerBlockType',
        'my-plugin/add-datatext-attribute',
        addDatatextAttribute
    );
    
    
    const withDatatextControl = createHigherOrderComponent((BlockEdit) => {
        return (props) => {
    
            console.log(props); // Check current props in console
            
            if (props.name !== 'core/rss') {
                return (<BlockEdit {...props} />)
            }
    
            return (
                <>
                    <BlockEdit {...props} />
                    <InspectorControls>
                        <PanelBody>
                            <TextControl
                                label="My Datatext"
                                value={props.attributes.datatext}
                                onChange={(value) => props.setAttributes({ datatext: value })}
                            />
                        </PanelBody>
                    </InspectorControls>
    
                </>
            );
        };
    }, 'withDatatextControl');
    
    addFilter(
        'editor.BlockEdit',
        'core/rss',
        withDatatextControl
    );
    
    Login or Signup to reply.
  2. To add a custom attribute to a core Gutenberg block, you need to do the following:

    1. Define the attribute in the block’s attributes object. In your case,
      it would look something like this:
    attributes: {
      columns: {
        type: 'number',
        default: 2,
      },
      blockLayout: {
        type: 'string',
        default: 'list',
      },
      feedURL: {
        type: 'string',
        default: 'example.com/blog/',
      },
      itemsToShow: {
        type: 'number',
        default: 5,
      },
      displayExcerpt: {
        type: 'boolean',
        default: false,
      },
      displayAuthor: {
        type: 'boolean',
        default: false,
      },
      displayDate: {
        type: 'boolean',
        default: false,
      },
      excerptLength: {
        type: 'number',
        default: 55,
      },
      datatext: {
        type: 'string',
        default: '',
      },
    },
    

    Note the addition of the datatext attribute, which has a default value of an empty string.

    1. In the block’s edit function, add the datatext attribute to the block’s props:
    function edit({ attributes, setAttributes }) {
      const { columns, blockLayout, feedURL, itemsToShow, displayExcerpt, displayAuthor, displayDate, excerptLength, datatext } = attributes;
    
      function onButtonClick() {
        // Handle button click and set the `datatext` attribute
        setAttributes({ datatext: 'your custom value' });
      }
    
      return (
        <div>
          <ToggleControl
            label="Your Toggle Button Label"
            checked={datatext !== ''}
            onChange={onButtonClick}
          />
          // Rest of the block's edit function code
        </div>
      );
    }
    

    Note the addition of the onButtonClick function, which sets the datatext attribute when the toggle button is clicked, and the use of the datatext attribute in the checked prop of the ToggleControl.

    1. In the block’s save function, include the datatext attribute in the block’s markup:
    function save({ attributes }) {
      const { columns, blockLayout, feedURL, itemsToShow, displayExcerpt, displayAuthor, displayDate, excerptLength, datatext } = attributes;
    
      return (
        <div data-datetext={datatext}>
          // Rest of the block's save function code
        </div>
      );
    }
    

    Note the addition of the data-datetext attribute, which includes the value of the datatext attribute.

    Here are some documentation where you can find out more on blocks in Guttenberg:

    1. WordPress Handbook on Block Editor: https://developer.wordpress.org/block-editor/
    2. Block Editor Handbook: https://developer.wordpress.org/block-editor/reference-guides/
    3. Gutenberg Plugin Handbook: https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/
    4. Gutenberg Developer Documentation: https://github.com/WordPress/gutenberg/tree/master/docs

    Keep in mind that modifying core blocks can sometimes cause unexpected issues, so it’s important to thoroughly test your changes before deploying them on a live site. Additionally, be sure to keep backups of your code and database in case anything goes wrong.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search