loading...

2021-10-16

Gutenberg blocks in WooCommerce

Gutenberg blocks in WooCommerce

Want to turn on Gutenberg while editing a WooCommerce product and use your blocks? Nothing easier!

First, I would not be able to show the class first, so see:

<?php

class GutenbergOnProduct
{
  public function __construct()
  {
    add_filter("use_block_editor_for_post_type", [$this, "activate_gutenberg_products"], 10, 2);
    add_filter("block_categories", [$this, "block_category"], 10, 2);
  }

  /**
   * @param $categories
   * @param $post
   * @return array|mixed
   */
  public function block_category($categories, $post) : array
  {
    if (in_array($post->post_type, ["page", "post", "product"])) {
      $blocks = array_merge(
        $categories,
        array(
          array(
            "slug" => "your_block_categories",
            "title" => __("YOUR NAME THEME", "theme"),
          )
        )
      );
    } else {
      return $categories;
    }

    return $blocks;
  }

  /**
   * @param $can_edit
   * @param $post_type
   * @return bool|mixed
   */
  public function activate_gutenberg_products($can_edit, $post_type): bool
  {
    if ($post_type === "product") {
      $can_edit = true;
    }

    return $can_edit;
  }
}

What do you think? Difficult? In my opinion, not at all. Now you have the option of using blocks when editing a product. Finally, a functional application:

<?php

add_filter("use_block_editor_for_post_type", "activate_gutenberg_products", 10, 2);
add_filter("block_categories", "block_category", 10, 2);


function block_category($categories, $post)
{
  if (in_array($post->post_type, ["page", "post", "product"])) {
    $blocks = array_merge(
      $categories,
      [
        [
          "slug" => "your_block_categories",
          "title" => __("YOUR NAME THEME", "theme"),
        ]
      ]
    );
  } else {
    return $categories;
  }

  return $blocks;
}

function activate_gutenberg_products($can_edit, $post_type)
{
  if ($post_type === "product") {
    $can_edit = true;
  }

  return $can_edit;
}

Do you have any problem? You need help? Contact me – we’ll do something.

Posted in Bez kategorii