Skip to content

Adding Custom Settings to WordPress Blocks – The Silly Way 🛠️🎨

Ahoy, fellow WordPress sailors! ⚓️ Are you tired of your WordPress blocks being all boring and basic? Do you want to sprinkle some magic pixie dust on them and make them custom, just like your playlist of “Songs to Cry to While Coding”? Well, buckle up because today we’re going on a magical journey to add custom settings to any WordPress block!

I promise to keep this blog funny, and maybe—just maybe—you’ll even learn something along the way. 😉

Table of Contents:

  1. What the Heck Are We Doing? 🤔
  2. Let’s Prep the Potion: Set Up Your Environment 🧪
  3. Identifying the Victim... I Mean, Block 🕵️‍♀️
  4. Enchanting the Block with Custom Attributes ✨
  5. Adding Custom Settings to the Block Editor – AKA The Fancy Sidebar 🏗️
  6. Saving Your Changes: Because We’re Not THAT Evil 🖋️
  7. Bonus: Add a Color Picker – Let’s Paint the Town Red 🎨
  8. Conclusion – You Are Now a Block Wizard 🧙‍♂️

What the Heck Are We Doing? 🤔

In this post, we’re going to take a plain old WordPress block—let’s say the boring “Paragraph Block” (yawn)—and add a little extra customization to it. Because, let’s face it, everything in life is better with a little customization, right? Even coffee.

We’re going to add custom attributes and settings to blocks, making your WordPress site look like it graduated from Hogwarts. 🧙‍♀️

Let’s Prep the Potion: Set Up Your Environment 🧪

First things first. We need to make sure everything is ready for our magical quest. Ensure that you have:

  • WordPress with Gutenberg enabled (otherwise, we’re just playing with the same old blocks!).
  • A custom plugin or theme’s functions.php to throw in our magic spells—uh, I mean JavaScript.

Here’s how to enqueue your custom JavaScript in WordPress:

php
function enqueue_custom_block_editor_script() {
    wp_enqueue_script(
        'custom-block-settings',
        plugin_dir_url( __FILE__ ) . 'assets/js/custom-block-settings.js', // Path to your JS file
        array( 'wp-blocks', 'wp-element', 'wp-hooks', 'wp-editor', 'wp-components' ),
        '1.0',
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'enqueue_custom_block_editor_script' );

We just summoned your JS file. 🧙‍♂️✨ Time to write some spells!

Identifying the Victim... I Mean, Block 🕵️‍♀️

Which block are we going to make more awesome? Let’s pick the core/paragraph block, AKA “Paragraph Block”. You know, that plain little block that’s just asking for some excitement.

But you can replace it with any other block—just like you’d replace your morning coffee with energy drinks on deadline day.

Enchanting the Block with Custom Attributes ✨

Now, here’s where the magic happens. We're going to add a custom attribute to this block. It’s like giving the block superpowers, but we get to choose what the superpower is!

js
function addCustomAttribute(settings, name) {
  if (name !== "core/paragraph") {
    // Replace with the block you want to customize
    return settings;
  }

  // Giving the block a new superpower
  settings.attributes.customAttributeName = {
    type: "string",
    default: "", // Starting value is boring, but we'll spice it up later!
  };

  return settings;
}

// Hook it into WordPress!
wp.hooks.addFilter(
  "blocks.registerBlockType",
  "custom/paragraph-custom-attribute",
  addCustomAttribute
);

Boom! We’ve just added a custom attribute, and now the block has customAttributeName. Next step: make it user-friendly, so even a Muggle can use it.

Adding Custom Settings to the Block Editor – AKA The Fancy Sidebar 🏗️

Now, let’s add some fancy pants settings to the block editor sidebar, so the user can interact with our custom attribute. Think of it as giving your block a control panel. 🚀

js
const withInspectorControls = wp.compose.createHigherOrderComponent(
  (BlockEdit) => {
    return (props) => {
      if (props.name !== "core/paragraph") {
        // Only do this for our block!
        return wp.element.createElement(BlockEdit, props);
      }

      const { attributes, setAttributes } = props;
      const { customAttributeName } = attributes;

      return wp.element.createElement(
        wp.element.Fragment,
        {},
        wp.element.createElement(BlockEdit, props), // Original block content
        wp.element.createElement(
          wp.blockEditor.InspectorControls,
          {}, // Here’s where the magic happens
          wp.element.createElement(
            wp.components.PanelBody,
            { title: "Custom Settings" },
            wp.element.createElement(wp.components.TextControl, {
              label: "Enter Custom Text",
              value: customAttributeName, // Our superpower
              onChange: (newValue) =>
                setAttributes({ customAttributeName: newValue }),
            })
          )
        )
      );
    };
  },
  "withInspectorControls"
);

// Hook it up, baby!
wp.hooks.addFilter(
  "editor.BlockEdit",
  "custom/paragraph-custom-control",
  withInspectorControls
);

Voilà! We’ve added a text field to the block settings, and now users can enter custom text. It’s like letting them choose their own superpower! 🦸‍♀️🦸‍♂️

Saving Your Changes: Because We’re Not THAT Evil 🖋️

Now, let’s make sure that our custom settings are saved when the block is updated. Otherwise, it’ll be like those moments when your code crashes but you forgot to hit “save” 2 hours ago. 😱

This happens automatically when we use setAttributes to update the custom attribute. No need for extra work! Your new block settings will be saved as part of the block’s attributes.

Bonus: Add a Color Picker – Let’s Paint the Town Red 🎨

Want to take things to the next level? Let’s throw in a color picker because, let’s be real, who doesn’t love colors? 🌈

js
(function (wp) {
  const { addFilter } = wp.hooks;
  const { createHigherOrderComponent } = wp.compose;
  const { InspectorControls } = wp.blockEditor;
  const { PanelBody, ColorPalette } = wp.components;

  // Step 1: Add Custom Color Attribute
  function addColorAttribute(settings, name) {
    if (name !== "core/paragraph") {
      return settings;
    }

    settings.attributes.customColor = {
      type: "string",
      default: "",
    };

    return settings;
  }

  addFilter(
    "blocks.registerBlockType",
    "custom/paragraph-color-attribute",
    addColorAttribute
  );

  // Step 2: Add Color Picker to Sidebar
  const withColorInspectorControls = createHigherOrderComponent((BlockEdit) => {
    return (props) => {
      if (props.name !== "core/paragraph") {
        return wp.element.createElement(BlockEdit, props);
      }

      const { attributes, setAttributes } = props;
      const { customColor } = attributes;

      return wp.element.createElement(
        wp.element.Fragment,
        {},
        wp.element.createElement(BlockEdit, props),
        wp.element.createElement(
          InspectorControls,
          {},
          wp.element.createElement(
            PanelBody,
            { title: "Custom Color" },
            wp.element.createElement(ColorPalette, {
              value: customColor,
              onChange: (newColor) => setAttributes({ customColor: newColor }),
            })
          )
        )
      );
    };
  }, "withColorInspectorControls");

  addFilter(
    "editor.BlockEdit",
    "custom/paragraph-color-control",
    withColorInspectorControls
  );
})(window.wp);

You’ve just added a color picker! Now users can paint their paragraphs in whatever color they want, just like how we paint our error messages in red when our code breaks. 😅

Conclusion – You Are Now a Block Wizard 🧙‍♂️

Congratulations! 🎉 You’ve just leveled up and become a Block Wizard. You now know how to:

  • Add custom attributes to WordPress blocks.
  • Create user-friendly settings in the block editor.
  • Save your changes like a responsible developer.
  • Add fancy color pickers because, let’s face it, colors are

Built by noobs, for noobs, with love 💻❤️