0

I am trying to create a custom gutenberg block for a school project. I am new to this and I have not used the @wordpress/create-block method. I have created a plugin with a test block manually with a php-, css and javascript file. The javascript uses wp.element.createElement methods to generate the block in the edit and save functions. Everything works there.

The PHP plugin file:

<?php
/**
* Plugin Name: Javascriptblock
* Description: JS Test
* Version: 1.0
* Author: Test
*/

if (!defined("ABSPATH")) {
  exit;
}

function javascriptblock() {

wp_register_script(
    "js-script",
    plugins_url("js.js", __FILE__),
    array("wp-blocks", "wp-components", "wp-element", "wp-i18n", "wp-editor"),
    filemtime(plugin_dir_path(__FILE__) . "js.js")
);

wp_register_style(
    "js-style",
    plugins_url("/js.css", __FILE__),
    array("wp-edit-blocks"),
    filemtime(plugin_dir_path(__FILE__) . "js.css")
);

register_block_type("javascriptblock/js", array(
    "editor_script" => "js-script",
    "editor_style"  => "js-style",
    "style"         => "js-style",
    "category"      => "common",
));
}
add_action("init", "javascriptblock");

And the Javascript for the block:

wp.blocks.registerBlockType("javascriptblock/javascriptblock", {
title: "Javascriptblock",
icon: "smiley",
category: "common",

edit: function () {
    return wp.element.createElement(
        "p",
        null,
        "Hello World"
    );
},

save: function () {
    return wp.element.createElement(
        "p",
        null,
        "Hello World!"
    );

    Test();
},
});

And finally the additional script that needs to be activated after the block renders:

function Test() {
  console.log("Working!");
}

How can I enqueue the Test function within the plugin?

1 Answer 1

1

The save function of blocks only saves markup to the database (along with HTML comments, which WP uses to parse the HTML back into the Editor). To use JS on the front end with your block, you will need to create a separate JS file for what needs to run there, and enqueue it so WordPress knows to include it.

2
  • Thank you! I suspected something like that was the case but I am not sure how to solve the problem. I have created a separate JS-file with a test function now that just console logs a string. How would I go about queing this script? I have updated my post with my plugin php file code and the javascript for the block and function.
    – user232026
    Commented May 4, 2023 at 6:12
  • 1
    There are lots of good examples if you search for how to enqueue a front end block script. gist.github.com/zgordon/561a82424e677a3b466d63fb588dddeb
    – WebElaine
    Commented May 4, 2023 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.