{"id":30786,"date":"2020-05-15T23:06:54","date_gmt":"2020-05-15T23:06:54","guid":{"rendered":"https:\/\/www.designbombs.com\/?p=30786"},"modified":"2020-05-17T08:52:05","modified_gmt":"2020-05-17T08:52:05","slug":"registering-gutenberg-blocks-for-custom-post-type","status":"publish","type":"post","link":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/","title":{"rendered":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)"},"content":{"rendered":"<p>When <a href=\"https:\/\/www.designbombs.com\/how-to-make-a-website\/\">creating a WordPress site<\/a>, we may need to create a custom post type and have it reference other entities from the database. For instance, a <code>Product<\/code> custom post, which displays how many stars it has been rated by the users, needs to reference a list of users or a list of <code>ProductReview<\/code> custom posts.<\/p>\n<p>WordPress provides custom meta fields, which enable to add any arbitrary piece of data to posts, users, comments, categories and tags, such as references to any other entity from the database. However, WordPress doesn&#8217;t provide a built-in solution to create the relationships across entities in the admin panel in a user-friendly way.<\/p>\n<p>This void has been filled by plugin <a href=\"https:\/\/www.advancedcustomfields.com\/\">Advanced Custom Fields<\/a>. Whenever we can control the environment where the site runs (such as when building a website for a client), we can install ACF and depend on it for creating all the relationships across entities.<\/p>\n<p>However, that is not the case when submitting a theme or plugin to the WordPress directory. Since we don&#8217;t know in advance if the user installing the theme or plugin will also have ACF installed, we must then find a different way to solve the problem.<\/p>\n<p>Luckily, <a href=\"https:\/\/wordpress.org\/gutenberg\/\">Gutenberg<\/a> can replace ACF (even though is not as simple, since it requires plenty of coding) by attaching custom blocks to the editor to let the user define the relationships across entities. For instance, the custom block can fetch the list of database entities that can be referenced using the WP REST API, display them on a select input, and save the selected entries through a block attribute.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-30788\" src=\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/gutenberg-block-referencing-entities.png\" alt=\"\" width=\"1134\" height=\"770\" srcset=\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/gutenberg-block-referencing-entities.png 1134w, https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/gutenberg-block-referencing-entities-300x204.png 300w, https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/gutenberg-block-referencing-entities-1024x695.png 1024w, https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/gutenberg-block-referencing-entities-768x521.png 768w\" sizes=\"auto, (max-width: 1134px) 100vw, 1134px\" \/><\/p>\n<p>Gutenberg will store the data within the post content, and we can retrieve it using <a href=\"https:\/\/developer.wordpress.org\/reference\/functions\/parse_blocks\/\">function <code>parse_blocks<\/code><\/a>, as we explained on article <a href=\"https:\/\/www.designbombs.com\/exposing-wordpress-site-data-for-mobile-apps\/\">Exposing WordPress site data for mobile apps<\/a>.<\/p>\n<p>This custom Gutenberg block makes sense only when editing the intended custom post type, so we need to remove it everywhere else. In this article, we will explore how to achieve this. We will first analyze the official solution, which is based on JavaScript, and then an alternative (and better) approach using PHP.<\/p>\n<h2>The official (unsatisfying) solution: Unregistering blocks through JavaScript code<\/h2>\n<p>The <a href=\"https:\/\/developer.wordpress.org\/block-editor\/developers\/filters\/block-filters\/#using-a-blacklist\">official solution<\/a> to this problem is to unregister the block by executing JavaScript function <code>wp.blocks.unregisterBlockType<\/code>:<\/p>\n<pre><code class=\"language-javascript\">wp.domReady( function() {\r\n  wp.blocks.unregisterBlockType( 'my-namespace\/my-custom-block' );\r\n} );\r\n<\/code><\/pre>\n<p>Please notice that there is also an alternative proposed approach, which is to <a href=\"https:\/\/developer.wordpress.org\/block-editor\/developers\/filters\/block-filters\/#using-a-whitelist\">use a whitelist<\/a>:<\/p>\n<pre><code class=\"language-javascript\">var allowedBlocks = [\r\n  'core\/paragraph',\r\n  'core\/image',\r\n  'core\/html',\r\n  'core\/freeform'\r\n];\r\n \r\nwp.blocks.getBlockTypes().forEach( function( blockType ) {\r\n  if ( allowedBlocks.indexOf( blockType.name ) === -1 ) {\r\n    wp.blocks.unregisterBlockType( blockType.name );\r\n  }\r\n} );\r\n<\/code><\/pre>\n<p>However, this approach will not work for our situation, because we only know which is the block type that is forbidden from all other custom post types, instead of knowing which are all the allowed block types. Sure, we could calculate the whitelist by removing the blacklisted block type from the list of all block types, but then we&#8217;d rather already use the simpler blacklisting approach.<\/p>\n<p>The blacklisting approach works, however I find this solution quite unsatisfactory, because of several reasons:<\/p>\n<ul>\n<li>First registering the block in PHP as to then unregister it in JavaScript is not very sensible<\/li>\n<li>The name of the post type is defined in PHP and referenced in JavaScript, so the code is not DRY (Don&#8217;t Repeat Yourself), which can potentially create bugs down the road if the developer is not careful and renames the post type in one place only<\/li>\n<li>Even though it won&#8217;t be executed, the script for the blacklisted block type is still loaded, affecting performance<\/li>\n<li>JavaScript requires extra steps (compilation, minifying, bundling, etc) over PHP, meaning more complexity and extra bureaucracy<\/li>\n<\/ul>\n<p>Resolving this problem in PHP, if possible, shold lead to a neater solution. Let&#8217;s explore how to do this.<\/p>\n<h2>First (failed) approach with PHP: Using hook <code>\"allowed_block_types\"<\/code><\/h2>\n<p>WordPress provides <a href=\"https:\/\/developer.wordpress.org\/reference\/hooks\/allowed_block_types\/\">filter <code>\"allowed_block_types\"<\/code><\/a> to modify what block types are allowed for a post.<\/p>\n<p>Whitelisting blocks can be easily accomplished, like this:<\/p>\n<pre><code class=\"language-php\">function wpdocs_allowed_block_types( $allowed_block_types, $post ) {\r\n  if ( $post-&gt;post_type !== 'post' ) {\r\n    return $allowed_block_types;\r\n  }\r\n\r\n  return array( 'core\/paragraph' );\r\n}\r\nadd_filter( 'allowed_block_types', 'wpdocs_allowed_block_types', 10, 2 );\r\n<\/code><\/pre>\n<p>Unfortunately, this filter does not work for the blacklisting approach, which is what we need. This is because the filter must return the whitelisted list of block types, to be calculated as all block types minus the blacklisted ones. However, this filter initially does not receive the array with all registered block types, but a <code>true<\/code> boolean value. Hence, it must first obtain the array of all blocks from somewhere in the system.<\/p>\n<p>Yet, this information is not available on the PHP-side of the admin panel! There is <a href=\"https:\/\/developer.wordpress.org\/reference\/classes\/wp_block_type_registry\/get_all_registered\/\">function <code>get_all_registered()<\/code> from <code>WP_Block_Type_Registry<\/code><\/a>, however it returns only blocks registered through <code>register_block_types<\/code>, and many core blocks (such as <code>\"core\/paragraph\"<\/code>) are not registered this way. Then, we would need to discover the list of all core blocks not registered with <code>register_block_types<\/code> and manually add them to the list, which leads to plenty of bureaucracy (such as having to watch future releases of WordPress to discover new unregistered core blocks and add them to the list), and bugs are bound to happen.<\/p>\n<p>So this approach doesn&#8217;t work. What else can we do?<\/p>\n<h2 id=\"blacklist-block-with-php\">Second (successful) approach with PHP: Register a block type only if the custom post type in editor is the right one<\/h2>\n<p>The WordPress editor knows which is the post type of the post being edited. Then, the solution is initially simple:<\/p>\n<ul>\n<li>In the editor, check which is the post type of the post being created or edited<\/li>\n<li>If it is the right CPT, only then register the block<\/li>\n<\/ul>\n<p>Unfortunately, there is no function similar to <code>is_singular($post_type)<\/code> for the admin panel, as to determine the post type of the object being edited. And even though the post type information is stored under global variable <code>$typenow<\/code>, this variable is set late in the process, and not before hook <code>\"init\"<\/code> is executed (which is where we normally place the logic to register the block scripts), so we can&#8217;t use this variable for our purpose.<\/p>\n<p>To solve this issue, we can recreate the logic to calculate the value for global variable <code>$typenow<\/code>. The steps to follow are:<\/p>\n<ol>\n<li>Check if we are on the admin panel<\/li>\n<li>Get the value of global variable <code>$pagenow<\/code> (which has been set by the time the <code>\"init\"<\/code> hook is invoked)<\/li>\n<li>Obtain the post type like this:\n<ul>\n<li>If the value of <code>$pagenow<\/code> is <code>\"post-new.php\"<\/code>, then the post type of the new post is indicated under URL parameter <code>'post_type'<\/code><\/li>\n<li>If instead it is <code>\"post.php\"<\/code>, then the post type can be deduced from the object being edited<\/li>\n<\/ul>\n<\/li>\n<li>If this is the intended custom post type, only then execute <code>register_block_type<\/code><\/li>\n<\/ol>\n<p>Here is the code:<\/p>\n<pre><code class=\"language-php\">add_action('init', 'maybe_register_custom_block');\r\nfunction maybe_register_custom_block()\r\n{\r\n  \/\/ Check if this is the intended custom post type\r\n  if (is_admin()) {\r\n    global $pagenow;\r\n    $typenow = '';\r\n    if ( 'post-new.php' === $pagenow ) {\r\n      if ( isset( $_REQUEST['post_type'] ) &amp;&amp; post_type_exists( $_REQUEST['post_type'] ) ) {\r\n        $typenow = $_REQUEST['post_type'];\r\n      };\r\n    } elseif ( 'post.php' === $pagenow ) {\r\n      if ( isset( $_GET['post'] ) &amp;&amp; isset( $_POST['post_ID'] ) &amp;&amp; (int) $_GET['post'] !== (int) $_POST['post_ID'] ) {\r\n        \/\/ Do nothing\r\n      } elseif ( isset( $_GET['post'] ) ) {\r\n        $post_id = (int) $_GET['post'];\r\n      } elseif ( isset( $_POST['post_ID'] ) ) {\r\n        $post_id = (int) $_POST['post_ID'];\r\n      }\r\n      if ( $post_id ) {\r\n        $post = get_post( $post_id );\r\n        $typenow = $post-&gt;post_type;\r\n      }\r\n    }\r\n    if ($typenow != 'my-custom-post-type') {\r\n      return;\r\n    }\r\n  }\r\n\r\n  \/\/ Register the block\r\n  $asset_file = include( plugin_dir_path( __FILE__ ) . 'build\/index.asset.php');\r\n  wp_register_script(\r\n    'my-custom-block',\r\n    plugins_url( 'build\/block.js', __FILE__ ),\r\n    $asset_file['dependencies'],\r\n    $asset_file['version']\r\n  );\r\n  register_block_type( 'my-namespace\/my-custom-block-name', array(\r\n    'editor_script' =&gt; 'my-custom-block',\r\n  ) );\r\n}\r\n<\/code><\/pre>\n<p>This solution is a bit hacky, but it works well.<\/p>\n<h2>Conclusion<\/h2>\n<p>Registering plenty of blocks in the Gutenberg editor can bog down the user experience. Then, it is a good practice to avoid registering blocks whenever they are not needed, such as when creating a custom block that needs be accessed for a specific custom post type only.<\/p>\n<p>The official way to do it, based on JavaScript code, is unsatisfactory, because it loads the unwanted scripts so performance still takes a hit, requires extra effort, and can lead to bugs.<\/p>\n<p>In this article we learnt that we can achieve it with PHP code, by deciding if to register the block type or not depending on the current post type in the editor. This method is more effective: performance improves since scripts are never loaded, and it is simpler to execute, overall making the application be more resilient.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When creating a WordPress site, we may need to create a custom post type and have it reference other entities&#8230;<\/p>\n","protected":false},"author":50,"featured_media":30793,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[51],"tags":[3168,11],"class_list":{"0":"post-30786","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-coding","8":"tag-gutenberg","9":"tag-wordpress","10":"entry"},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v18.1 (Yoast SEO v26.4) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)<\/title>\n<meta name=\"description\" content=\"The official way to register Gutenberg blocks for certain custom post types only requires JavaScript, but PHP can provide a finer solution.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)\" \/>\n<meta property=\"og:description\" content=\"When creating a WordPress site, we may need to create a custom post type and have it reference other entities from the database. For instance, a Product\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\" \/>\n<meta property=\"og:site_name\" content=\"Design Bombs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/designbombs\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-05-15T23:06:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-05-17T08:52:05+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png\" \/>\n\t<meta property=\"og:image:width\" content=\"722\" \/>\n\t<meta property=\"og:image:height\" content=\"300\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Leonardo Losoviz\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@losoviz\" \/>\n<meta name=\"twitter:site\" content=\"@designbombs\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Leonardo Losoviz\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\"},\"author\":{\"name\":\"Leonardo Losoviz\",\"@id\":\"https:\/\/www.designbombs.com\/#\/schema\/person\/4259b761dbd3ee01f8c7e2cd9d74df39\"},\"headline\":\"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)\",\"datePublished\":\"2020-05-15T23:06:54+00:00\",\"dateModified\":\"2020-05-17T08:52:05+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\"},\"wordCount\":1191,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/www.designbombs.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png\",\"keywords\":[\"gutenberg\",\"wordpress\"],\"articleSection\":[\"Coding\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\",\"url\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\",\"name\":\"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)\",\"isPartOf\":{\"@id\":\"https:\/\/www.designbombs.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png\",\"datePublished\":\"2020-05-15T23:06:54+00:00\",\"dateModified\":\"2020-05-17T08:52:05+00:00\",\"description\":\"The official way to register Gutenberg blocks for certain custom post types only requires JavaScript, but PHP can provide a finer solution.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage\",\"url\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png\",\"contentUrl\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png\",\"width\":722,\"height\":300,\"caption\":\"Registering Gutenberg blocks for some Custom Post Type only\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.designbombs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Coding\",\"item\":\"https:\/\/www.designbombs.com\/category\/coding\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.designbombs.com\/#website\",\"url\":\"https:\/\/www.designbombs.com\/\",\"name\":\"Design Bombs\",\"description\":\"Droppin&#039; design bombs everyday!\",\"publisher\":{\"@id\":\"https:\/\/www.designbombs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.designbombs.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.designbombs.com\/#organization\",\"name\":\"DesignBombs\",\"url\":\"https:\/\/www.designbombs.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.designbombs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2019\/04\/db-logo.png\",\"contentUrl\":\"https:\/\/www.designbombs.com\/wp-content\/uploads\/2019\/04\/db-logo.png\",\"width\":219,\"height\":92,\"caption\":\"DesignBombs\"},\"image\":{\"@id\":\"https:\/\/www.designbombs.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/designbombs\/\",\"https:\/\/x.com\/designbombs\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.designbombs.com\/#\/schema\/person\/4259b761dbd3ee01f8c7e2cd9d74df39\",\"name\":\"Leonardo Losoviz\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.designbombs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/bb059a4470fd73113804d5dd7430f6a66aaba66ba161798d0fac79b124c74611?s=96&d=https%3A%2F%2Fwww.designbombs.com%2Fwp-content%2Fthemes%2FDesignBombs%2Fimages%2Fgravatar.jpg&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/bb059a4470fd73113804d5dd7430f6a66aaba66ba161798d0fac79b124c74611?s=96&d=https%3A%2F%2Fwww.designbombs.com%2Fwp-content%2Fthemes%2FDesignBombs%2Fimages%2Fgravatar.jpg&r=g\",\"caption\":\"Leonardo Losoviz\"},\"description\":\"Leonardo Losoviz is an open source developer and technical writer, author of GraphQL by PoP, a CMS-agnostic GraphQL server in PHP. Find him on his blog leoloso.com and on Twitter @losoviz.\",\"sameAs\":[\"https:\/\/leoloso.com\",\"https:\/\/x.com\/losoviz\"],\"url\":\"https:\/\/www.designbombs.com\/author\/leo\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)","description":"The official way to register Gutenberg blocks for certain custom post types only requires JavaScript, but PHP can provide a finer solution.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/","og_locale":"en_US","og_type":"article","og_title":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)","og_description":"When creating a WordPress site, we may need to create a custom post type and have it reference other entities from the database. For instance, a Product","og_url":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/","og_site_name":"Design Bombs","article_publisher":"https:\/\/www.facebook.com\/designbombs\/","article_published_time":"2020-05-15T23:06:54+00:00","article_modified_time":"2020-05-17T08:52:05+00:00","og_image":[{"width":722,"height":300,"url":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","type":"image\/png"}],"author":"Leonardo Losoviz","twitter_card":"summary_large_image","twitter_creator":"@losoviz","twitter_site":"@designbombs","twitter_misc":{"Written by":"Leonardo Losoviz","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#article","isPartOf":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/"},"author":{"name":"Leonardo Losoviz","@id":"https:\/\/www.designbombs.com\/#\/schema\/person\/4259b761dbd3ee01f8c7e2cd9d74df39"},"headline":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)","datePublished":"2020-05-15T23:06:54+00:00","dateModified":"2020-05-17T08:52:05+00:00","mainEntityOfPage":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/"},"wordCount":1191,"commentCount":1,"publisher":{"@id":"https:\/\/www.designbombs.com\/#organization"},"image":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage"},"thumbnailUrl":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","keywords":["gutenberg","wordpress"],"articleSection":["Coding"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/","url":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/","name":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)","isPartOf":{"@id":"https:\/\/www.designbombs.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage"},"image":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage"},"thumbnailUrl":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","datePublished":"2020-05-15T23:06:54+00:00","dateModified":"2020-05-17T08:52:05+00:00","description":"The official way to register Gutenberg blocks for certain custom post types only requires JavaScript, but PHP can provide a finer solution.","breadcrumb":{"@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#primaryimage","url":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","contentUrl":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","width":722,"height":300,"caption":"Registering Gutenberg blocks for some Custom Post Type only"},{"@type":"BreadcrumbList","@id":"https:\/\/www.designbombs.com\/registering-gutenberg-blocks-for-custom-post-type\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.designbombs.com\/"},{"@type":"ListItem","position":2,"name":"Coding","item":"https:\/\/www.designbombs.com\/category\/coding\/"},{"@type":"ListItem","position":3,"name":"How to Register Gutenberg Blocks for Some Custom Post Type only, using PHP (not JS!)"}]},{"@type":"WebSite","@id":"https:\/\/www.designbombs.com\/#website","url":"https:\/\/www.designbombs.com\/","name":"Design Bombs","description":"Droppin&#039; design bombs everyday!","publisher":{"@id":"https:\/\/www.designbombs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.designbombs.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.designbombs.com\/#organization","name":"DesignBombs","url":"https:\/\/www.designbombs.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.designbombs.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2019\/04\/db-logo.png","contentUrl":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2019\/04\/db-logo.png","width":219,"height":92,"caption":"DesignBombs"},"image":{"@id":"https:\/\/www.designbombs.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/designbombs\/","https:\/\/x.com\/designbombs"]},{"@type":"Person","@id":"https:\/\/www.designbombs.com\/#\/schema\/person\/4259b761dbd3ee01f8c7e2cd9d74df39","name":"Leonardo Losoviz","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.designbombs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/bb059a4470fd73113804d5dd7430f6a66aaba66ba161798d0fac79b124c74611?s=96&d=https%3A%2F%2Fwww.designbombs.com%2Fwp-content%2Fthemes%2FDesignBombs%2Fimages%2Fgravatar.jpg&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/bb059a4470fd73113804d5dd7430f6a66aaba66ba161798d0fac79b124c74611?s=96&d=https%3A%2F%2Fwww.designbombs.com%2Fwp-content%2Fthemes%2FDesignBombs%2Fimages%2Fgravatar.jpg&r=g","caption":"Leonardo Losoviz"},"description":"Leonardo Losoviz is an open source developer and technical writer, author of GraphQL by PoP, a CMS-agnostic GraphQL server in PHP. Find him on his blog leoloso.com and on Twitter @losoviz.","sameAs":["https:\/\/leoloso.com","https:\/\/x.com\/losoviz"],"url":"https:\/\/www.designbombs.com\/author\/leo\/"}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/www.designbombs.com\/wp-content\/uploads\/2020\/05\/Registering-Gutenberg-blocks-for-some-Custom-Post-Type-only.png","jetpack-related-posts":[],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/posts\/30786","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/users\/50"}],"replies":[{"embeddable":true,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/comments?post=30786"}],"version-history":[{"count":3,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/posts\/30786\/revisions"}],"predecessor-version":[{"id":30797,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/posts\/30786\/revisions\/30797"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/media\/30793"}],"wp:attachment":[{"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/media?parent=30786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/categories?post=30786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.designbombs.com\/wp-json\/wp\/v2\/tags?post=30786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}