【问题标题】:Run a piece of code when block is loaded in wordpress在 wordpress 中加载块时运行一段代码
【发布时间】:2020-04-04 13:56:59
【问题描述】:

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

(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 时才有效。

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

【问题讨论】:

    标签: wordpress block wordpress-gutenberg gutenberg-blocks create-guten-block


    【解决方案1】:

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

    【讨论】:

    • 你能举个例子吗?我对 wordpress 古腾堡了解不多。
    • 我已经修改了我的答案。请检查。
    • 您可以在这里查看实时代码。如果你想深入了解一下。 github.com/BRdhanani/gutenberg-recent-posts/blob/master/src/…
    • 属性是您在 js 文件中定义的道具。例如: $attributes['headline'] 在你的情况下。
    • 你绝对可以在PHP文件中添加js代码。但是在PHP文件中使用js代码并不标准。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多