运行 wordpress加载block时的一段代码

Run a piece of code when block is loaded in wordpress

我制作了一个自定义的古腾堡块:

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

我想在前端加载块时运行一个函数。

我在 save 函数中尝试过,但只有当块保存在 wp-dashboard 上时它才有效。

有什么方法可以在加载块时 运行 函数?

您可以在 PHP 文件中的寄存器块类型中使用渲染回调参数。 喜欢

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

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