首页 > 解决方案 > 在 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 上时它才有效。

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

标签: wordpressblockwordpress-gutenberggutenberg-blockscreate-guten-block

解决方案


您可以在 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
}

推荐阅读