Block Bindings Source: Main Category
Registers a block bindings source that shows a post's main category name, link or description in any paragraph, heading or button, for example as a label above titles in a Query Loop.
Opens WPIDE on
Code
add_action( 'init', function () {
if ( ! function_exists( 'register_block_bindings_source' ) ) {
return;
}
register_block_bindings_source( 'wpide/category', array(
'label' => 'Main category',
'uses_context' => array( 'postId' ),
'get_value_callback' => function ( $args, $block ) {
$post_id = ! empty( $block->context['postId'] ) ? (int) $block->context['postId'] : get_the_ID();
$categories = get_the_category( $post_id );
if ( ! $categories ) {
return null;
}
$category = $categories[0];
switch ( $args['key'] ?? 'name' ) {
case 'link':
return esc_url( get_category_link( $category ) );
case 'description':
return esc_html( wp_strip_all_tags( category_description( $category ) ) );
default:
return esc_html( $category->name );
}
},
) );
} );
Notes
Needs WordPress 6.5+; bind with "source":"wpide/category" and args {"key":"name"} (also link, description). The first category alphabetically is used.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.