Skip to content

Extending All Blocks to a Post Type

Custom built blocks can be extended for use on custom post types individually in the block.json, however, it would be tedious to do this for every block if all of them needed to be available to a specific custom post type. Instead you can extend the availablity of all blocks to a post type with a hook like the one below.

<?php

namespace Origins\Hooks;

use Og\Interfaces\ActionInterface;
use Og\Interfaces\FilterInterface;
use Og\Traits\Actions;
use Og\Traits\Filters;

class GlobalBlocks implements ActionInterface, FilterInterface {
    use Actions, Filters;
    private $global_post_types = [
        'tenant-portal'
    ];

    public function should_load() : bool {
        return true;
    }
    public function load() {

            $this->add_filter('block_type_metadata', [$this, 'add_global_post_type_for_og_blocks'], 10, 1);

    }

    public function add_global_post_type_for_og_blocks($metadata) {

        if (!isset($metadata['name'])) {
            return $metadata;
        }

        $block_name = $metadata['name'];

        if (strpos($block_name, 'og/') !== 0) {
            return $metadata;
        }
        $metadata['acf']['postTypes'] = array_merge($metadata['acf']['postTypes'], $this->global_post_types);
       return $metadata;
    }
}