generated-classname.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Generated classname block support flag.
  4. *
  5. * @package WordPress
  6. * @since 5.6.0
  7. */
  8. /**
  9. * Get the generated classname from a given block name.
  10. *
  11. * @since 5.6.0
  12. *
  13. * @access private
  14. *
  15. * @param string $block_name Block Name.
  16. * @return string Generated classname.
  17. */
  18. function wp_get_block_default_classname( $block_name ) {
  19. // Generated HTML classes for blocks follow the `wp-block-{name}` nomenclature.
  20. // Blocks provided by WordPress drop the prefixes 'core/' or 'core-' (historically used in 'core-embed/').
  21. $classname = 'wp-block-' . preg_replace(
  22. '/^core-/',
  23. '',
  24. str_replace( '/', '-', $block_name )
  25. );
  26. /**
  27. * Filters the default block className for server rendered blocks.
  28. *
  29. * @since 5.6.0
  30. *
  31. * @param string $class_name The current applied classname.
  32. * @param string $block_name The block name.
  33. */
  34. $classname = apply_filters( 'block_default_classname', $classname, $block_name );
  35. return $classname;
  36. }
  37. /**
  38. * Add the generated classnames to the output.
  39. *
  40. * @since 5.6.0
  41. *
  42. * @access private
  43. *
  44. * @param WP_Block_Type $block_type Block Type.
  45. *
  46. * @return array Block CSS classes and inline styles.
  47. */
  48. function wp_apply_generated_classname_support( $block_type ) {
  49. $attributes = array();
  50. $has_generated_classname_support = block_has_support( $block_type, array( 'className' ), true );
  51. if ( $has_generated_classname_support ) {
  52. $block_classname = wp_get_block_default_classname( $block_type->name );
  53. if ( $block_classname ) {
  54. $attributes['class'] = $block_classname;
  55. }
  56. }
  57. return $attributes;
  58. }
  59. // Register the block support.
  60. WP_Block_Supports::get_instance()->register(
  61. 'generated-classname',
  62. array(
  63. 'apply' => 'wp_apply_generated_classname_support',
  64. )
  65. );