Run a piece of code when block is loaded in wordpress

1.9k views Asked by At

I have made a custom gutenberg block:

(function(blocks, components, element) {
  var el = element.createElement;
  var registerBlockType = blocks.registerBlockType;
  var TextControl = components.TextControl;

  registerBlockType("blocks/test-block", {
    title: "Test Block",
    description: "A custom block.",
    icon: "businessman",
    category: "common",
    attributes: {
      headline: {
        type: "string"
      }
    },

    edit: function(props) {
      var headline = props.attributes.headline;
      var onHeadlineChange = function(val) {
        props.setAttributes({
          headline: val
        });
      };

      return el(TextControl, {
        value: headline,
        label: "Headline",
        onChange: onHeadlineChange
      });
    },
    save: function(props) {
      alert('');
      return el(
        "h3",
        {
          className: "headline"
        },
        props.attributes.headline
      );
    }
  });
})(window.wp.blocks, window.wp.components, window.wp.element);

I want to run a function when the block is loaded on front end.

I tried in save function but it only work when the block is saved on wp-dashboard.

Is there any way by which I can run a function when block is loaded?

1

There are 1 answers

9
Brijesh Dhanani On BEST ANSWER

You can use render callback parameter in register block type inside your PHP file. like

register_block_type(
    'blocks/test-block', array(
        'editor_script' => 'index-js',
        'render_callback' => 'recent_posts_block'
    )
);

function recent_posts_block($attributes){
//your code here
}