Using WordPress ‘get_block_categories()’ PHP function

The get_block_categories() WordPress PHP function returns all the categories for block types that will be shown in the block editor.

Usage

get_block_categories( $post_or_block_editor_context );

Custom example

$block_categories = get_block_categories( $post );
foreach ( $block_categories as $category ) {
    echo $category->slug . ': ' . $category->title . '<br>';
}

Parameters

  • $post_or_block_editor_context (WP_Post|WP_Block_Editor_Context): The current post object or the block editor context.

More information

See WordPress Developer Resources: get_block_categories()

Examples

Display block categories in a post

function display_block_categories_in_post() {
    $post = get_post();
    $block_categories = get_block_categories( $post );

    foreach ( $block_categories as $category ) {
        echo '<strong>' . $category->title . '</strong><br>';
    }
}
add_action( 'the_content', 'display_block_categories_in_post' );

Add a custom block category

function my_custom_block_categories( $categories, $post ) {
    return array_merge(
        $categories,
        array(
            array(
                'slug' => 'my-custom-category',
                'title' => 'My Custom Category',
            ),
        )
    );
}
add_filter( 'block_categories_all', 'my_custom_block_categories', 10, 2 );

Remove a block category

function remove_block_category( $categories, $post ) {
    return array_filter(
        $categories,
        function ( $category ) {
            return $category->slug !== 'category-to-remove';
        }
    );
}
add_filter( 'block_categories_all', 'remove_block_category', 10, 2 );

Change block category title

function change_block_category_title( $categories, $post ) {
    foreach ( $categories as $category ) {
        if ( $category->slug === 'category-to-change' ) {
            $category->title = 'New Title';
        }
    }
    return $categories;
}
add_filter( 'block_categories_all', 'change_block_category_title', 10, 2 );

Sort block categories alphabetically

function sort_block_categories_alphabetically( $categories, $post ) {
    usort(
        $categories,
        function ( $a, $b ) {
            return strcmp( $a->title, $b->title );
        }
    );
    return $categories;
}
add_filter( 'block_categories_all', 'sort_block_categories_alphabetically', 10, 2 );