blocks.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. <?php
  2. /**
  3. * Functions related to registering and parsing blocks.
  4. *
  5. * @package WordPress
  6. * @subpackage Blocks
  7. * @since 5.0.0
  8. */
  9. /**
  10. * Removes the block asset's path prefix if provided.
  11. *
  12. * @since 5.5.0
  13. *
  14. * @param string $asset_handle_or_path Asset handle or prefixed path.
  15. * @return string Path without the prefix or the original value.
  16. */
  17. function remove_block_asset_path_prefix( $asset_handle_or_path ) {
  18. $path_prefix = 'file:';
  19. if ( 0 !== strpos( $asset_handle_or_path, $path_prefix ) ) {
  20. return $asset_handle_or_path;
  21. }
  22. $path = substr(
  23. $asset_handle_or_path,
  24. strlen( $path_prefix )
  25. );
  26. if ( strpos( $path, './' ) === 0 ) {
  27. $path = substr( $path, 2 );
  28. }
  29. return $path;
  30. }
  31. /**
  32. * Generates the name for an asset based on the name of the block
  33. * and the field name provided.
  34. *
  35. * @since 5.5.0
  36. * @since 6.1.0 Added `$index` parameter.
  37. *
  38. * @param string $block_name Name of the block.
  39. * @param string $field_name Name of the metadata field.
  40. * @param int $index Optional. Index of the asset when multiple items passed.
  41. * Default 0.
  42. * @return string Generated asset name for the block's field.
  43. */
  44. function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) {
  45. if ( 0 === strpos( $block_name, 'core/' ) ) {
  46. $asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
  47. if ( 0 === strpos( $field_name, 'editor' ) ) {
  48. $asset_handle .= '-editor';
  49. }
  50. if ( 0 === strpos( $field_name, 'view' ) ) {
  51. $asset_handle .= '-view';
  52. }
  53. if ( $index > 0 ) {
  54. $asset_handle .= '-' . ( $index + 1 );
  55. }
  56. return $asset_handle;
  57. }
  58. $field_mappings = array(
  59. 'editorScript' => 'editor-script',
  60. 'script' => 'script',
  61. 'viewScript' => 'view-script',
  62. 'editorStyle' => 'editor-style',
  63. 'style' => 'style',
  64. );
  65. $asset_handle = str_replace( '/', '-', $block_name ) .
  66. '-' . $field_mappings[ $field_name ];
  67. if ( $index > 0 ) {
  68. $asset_handle .= '-' . ( $index + 1 );
  69. }
  70. return $asset_handle;
  71. }
  72. /**
  73. * Finds a script handle for the selected block metadata field. It detects
  74. * when a path to file was provided and finds a corresponding asset file
  75. * with details necessary to register the script under automatically
  76. * generated handle name. It returns unprocessed script handle otherwise.
  77. *
  78. * @since 5.5.0
  79. * @since 6.1.0 Added `$index` parameter.
  80. *
  81. * @param array $metadata Block metadata.
  82. * @param string $field_name Field name to pick from metadata.
  83. * @param int $index Optional. Index of the script to register when multiple items passed.
  84. * Default 0.
  85. * @return string|false Script handle provided directly or created through
  86. * script's registration, or false on failure.
  87. */
  88. function register_block_script_handle( $metadata, $field_name, $index = 0 ) {
  89. if ( empty( $metadata[ $field_name ] ) ) {
  90. return false;
  91. }
  92. $script_handle = $metadata[ $field_name ];
  93. if ( is_array( $script_handle ) ) {
  94. if ( empty( $script_handle[ $index ] ) ) {
  95. return false;
  96. }
  97. $script_handle = $script_handle[ $index ];
  98. }
  99. $script_path = remove_block_asset_path_prefix( $script_handle );
  100. if ( $script_handle === $script_path ) {
  101. return $script_handle;
  102. }
  103. $script_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index );
  104. $script_asset_path = wp_normalize_path(
  105. realpath(
  106. dirname( $metadata['file'] ) . '/' .
  107. substr_replace( $script_path, '.asset.php', - strlen( '.js' ) )
  108. )
  109. );
  110. if ( ! file_exists( $script_asset_path ) ) {
  111. _doing_it_wrong(
  112. __FUNCTION__,
  113. sprintf(
  114. /* translators: 1: Field name, 2: Block name. */
  115. __( 'The asset file for the "%1$s" defined in "%2$s" block definition is missing.' ),
  116. $field_name,
  117. $metadata['name']
  118. ),
  119. '5.5.0'
  120. );
  121. return false;
  122. }
  123. // Path needs to be normalized to work in Windows env.
  124. static $wpinc_path_norm = '';
  125. if ( ! $wpinc_path_norm ) {
  126. $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
  127. }
  128. $theme_path_norm = wp_normalize_path( get_theme_file_path() );
  129. $script_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $script_path ) );
  130. $is_core_block = isset( $metadata['file'] ) && 0 === strpos( $metadata['file'], $wpinc_path_norm );
  131. $is_theme_block = 0 === strpos( $script_path_norm, $theme_path_norm );
  132. $script_uri = plugins_url( $script_path, $metadata['file'] );
  133. if ( $is_core_block ) {
  134. $script_uri = includes_url( str_replace( $wpinc_path_norm, '', $script_path_norm ) );
  135. } elseif ( $is_theme_block ) {
  136. $script_uri = get_theme_file_uri( str_replace( $theme_path_norm, '', $script_path_norm ) );
  137. }
  138. $script_asset = require $script_asset_path;
  139. $script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array();
  140. $result = wp_register_script(
  141. $script_handle,
  142. $script_uri,
  143. $script_dependencies,
  144. isset( $script_asset['version'] ) ? $script_asset['version'] : false
  145. );
  146. if ( ! $result ) {
  147. return false;
  148. }
  149. if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) {
  150. wp_set_script_translations( $script_handle, $metadata['textdomain'] );
  151. }
  152. return $script_handle;
  153. }
  154. /**
  155. * Finds a style handle for the block metadata field. It detects when a path
  156. * to file was provided and registers the style under automatically
  157. * generated handle name. It returns unprocessed style handle otherwise.
  158. *
  159. * @since 5.5.0
  160. * @since 6.1.0 Added `$index` parameter.
  161. *
  162. * @param array $metadata Block metadata.
  163. * @param string $field_name Field name to pick from metadata.
  164. * @param int $index Optional. Index of the style to register when multiple items passed.
  165. * Default 0.
  166. * @return string|false Style handle provided directly or created through
  167. * style's registration, or false on failure.
  168. */
  169. function register_block_style_handle( $metadata, $field_name, $index = 0 ) {
  170. if ( empty( $metadata[ $field_name ] ) ) {
  171. return false;
  172. }
  173. static $wpinc_path_norm = '';
  174. if ( ! $wpinc_path_norm ) {
  175. $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
  176. }
  177. $is_core_block = isset( $metadata['file'] ) && 0 === strpos( $metadata['file'], $wpinc_path_norm );
  178. // Skip registering individual styles for each core block when a bundled version provided.
  179. if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) {
  180. return false;
  181. }
  182. $style_handle = $metadata[ $field_name ];
  183. if ( is_array( $style_handle ) ) {
  184. if ( empty( $style_handle[ $index ] ) ) {
  185. return false;
  186. }
  187. $style_handle = $style_handle[ $index ];
  188. }
  189. $style_path = remove_block_asset_path_prefix( $style_handle );
  190. $is_style_handle = $style_handle === $style_path;
  191. // Allow only passing style handles for core blocks.
  192. if ( $is_core_block && ! $is_style_handle ) {
  193. return false;
  194. }
  195. // Return the style handle unless it's the first item for every core block that requires special treatment.
  196. if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) {
  197. return $style_handle;
  198. }
  199. // Check whether styles should have a ".min" suffix or not.
  200. $suffix = SCRIPT_DEBUG ? '' : '.min';
  201. if ( $is_core_block ) {
  202. $style_path = "style$suffix.css";
  203. }
  204. $style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) );
  205. $has_style_file = '' !== $style_path_norm;
  206. if ( $has_style_file ) {
  207. $style_uri = plugins_url( $style_path, $metadata['file'] );
  208. // Cache $theme_path_norm to avoid calling get_theme_file_path() multiple times.
  209. static $theme_path_norm = '';
  210. if ( ! $theme_path_norm ) {
  211. $theme_path_norm = wp_normalize_path( get_theme_file_path() );
  212. }
  213. $is_theme_block = str_starts_with( $style_path_norm, $theme_path_norm );
  214. if ( $is_theme_block ) {
  215. $style_uri = get_theme_file_uri( str_replace( $theme_path_norm, '', $style_path_norm ) );
  216. } elseif ( $is_core_block ) {
  217. $style_uri = includes_url( 'blocks/' . str_replace( 'core/', '', $metadata['name'] ) . "/style$suffix.css" );
  218. }
  219. } else {
  220. $style_uri = false;
  221. }
  222. $style_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index );
  223. $version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false;
  224. $result = wp_register_style(
  225. $style_handle,
  226. $style_uri,
  227. array(),
  228. $version
  229. );
  230. if ( ! $result ) {
  231. return false;
  232. }
  233. if ( $has_style_file ) {
  234. wp_style_add_data( $style_handle, 'path', $style_path_norm );
  235. $rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm );
  236. if ( is_rtl() && file_exists( $rtl_file ) ) {
  237. wp_style_add_data( $style_handle, 'rtl', 'replace' );
  238. wp_style_add_data( $style_handle, 'suffix', $suffix );
  239. wp_style_add_data( $style_handle, 'path', $rtl_file );
  240. }
  241. }
  242. return $style_handle;
  243. }
  244. /**
  245. * Gets i18n schema for block's metadata read from `block.json` file.
  246. *
  247. * @since 5.9.0
  248. *
  249. * @return object The schema for block's metadata.
  250. */
  251. function get_block_metadata_i18n_schema() {
  252. static $i18n_block_schema;
  253. if ( ! isset( $i18n_block_schema ) ) {
  254. $i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' );
  255. }
  256. return $i18n_block_schema;
  257. }
  258. /**
  259. * Registers a block type from the metadata stored in the `block.json` file.
  260. *
  261. * @since 5.5.0
  262. * @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields.
  263. * @since 5.9.0 Added support for `variations` and `viewScript` fields.
  264. * @since 6.1.0 Added support for `render` field.
  265. *
  266. * @param string $file_or_folder Path to the JSON file with metadata definition for
  267. * the block or path to the folder where the `block.json` file is located.
  268. * If providing the path to a JSON file, the filename must end with `block.json`.
  269. * @param array $args Optional. Array of block type arguments. Accepts any public property
  270. * of `WP_Block_Type`. See WP_Block_Type::__construct() for information
  271. * on accepted arguments. Default empty array.
  272. * @return WP_Block_Type|false The registered block type on success, or false on failure.
  273. */
  274. function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
  275. /*
  276. * Get an array of metadata from a PHP file.
  277. * This improves performance for core blocks as it's only necessary to read a single PHP file
  278. * instead of reading a JSON file per-block, and then decoding from JSON to PHP.
  279. * Using a static variable ensures that the metadata is only read once per request.
  280. */
  281. static $core_blocks_meta;
  282. if ( ! $core_blocks_meta ) {
  283. $core_blocks_meta = include_once ABSPATH . WPINC . '/blocks/blocks-json.php';
  284. }
  285. $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ?
  286. trailingslashit( $file_or_folder ) . 'block.json' :
  287. $file_or_folder;
  288. if ( ! file_exists( $metadata_file ) ) {
  289. return false;
  290. }
  291. // Try to get metadata from the static cache for core blocks.
  292. $metadata = false;
  293. if ( str_starts_with( $file_or_folder, ABSPATH . WPINC ) ) {
  294. $core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder );
  295. if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) {
  296. $metadata = $core_blocks_meta[ $core_block_name ];
  297. }
  298. }
  299. // If metadata is not found in the static cache, read it from the file.
  300. if ( ! $metadata ) {
  301. $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) );
  302. }
  303. if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) {
  304. return false;
  305. }
  306. $metadata['file'] = wp_normalize_path( realpath( $metadata_file ) );
  307. /**
  308. * Filters the metadata provided for registering a block type.
  309. *
  310. * @since 5.7.0
  311. *
  312. * @param array $metadata Metadata for registering a block type.
  313. */
  314. $metadata = apply_filters( 'block_type_metadata', $metadata );
  315. // Add `style` and `editor_style` for core blocks if missing.
  316. if ( ! empty( $metadata['name'] ) && 0 === strpos( $metadata['name'], 'core/' ) ) {
  317. $block_name = str_replace( 'core/', '', $metadata['name'] );
  318. if ( ! isset( $metadata['style'] ) ) {
  319. $metadata['style'] = "wp-block-$block_name";
  320. }
  321. if ( ! isset( $metadata['editorStyle'] ) ) {
  322. $metadata['editorStyle'] = "wp-block-{$block_name}-editor";
  323. }
  324. }
  325. $settings = array();
  326. $property_mappings = array(
  327. 'apiVersion' => 'api_version',
  328. 'title' => 'title',
  329. 'category' => 'category',
  330. 'parent' => 'parent',
  331. 'ancestor' => 'ancestor',
  332. 'icon' => 'icon',
  333. 'description' => 'description',
  334. 'keywords' => 'keywords',
  335. 'attributes' => 'attributes',
  336. 'providesContext' => 'provides_context',
  337. 'usesContext' => 'uses_context',
  338. 'supports' => 'supports',
  339. 'styles' => 'styles',
  340. 'variations' => 'variations',
  341. 'example' => 'example',
  342. );
  343. $textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null;
  344. $i18n_schema = get_block_metadata_i18n_schema();
  345. foreach ( $property_mappings as $key => $mapped_key ) {
  346. if ( isset( $metadata[ $key ] ) ) {
  347. $settings[ $mapped_key ] = $metadata[ $key ];
  348. if ( $textdomain && isset( $i18n_schema->$key ) ) {
  349. $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain );
  350. }
  351. }
  352. }
  353. $script_fields = array(
  354. 'editorScript' => 'editor_script_handles',
  355. 'script' => 'script_handles',
  356. 'viewScript' => 'view_script_handles',
  357. );
  358. foreach ( $script_fields as $metadata_field_name => $settings_field_name ) {
  359. if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
  360. $scripts = $metadata[ $metadata_field_name ];
  361. $processed_scripts = array();
  362. if ( is_array( $scripts ) ) {
  363. for ( $index = 0; $index < count( $scripts ); $index++ ) {
  364. $result = register_block_script_handle(
  365. $metadata,
  366. $metadata_field_name,
  367. $index
  368. );
  369. if ( $result ) {
  370. $processed_scripts[] = $result;
  371. }
  372. }
  373. } else {
  374. $result = register_block_script_handle(
  375. $metadata,
  376. $metadata_field_name
  377. );
  378. if ( $result ) {
  379. $processed_scripts[] = $result;
  380. }
  381. }
  382. $settings[ $settings_field_name ] = $processed_scripts;
  383. }
  384. }
  385. $style_fields = array(
  386. 'editorStyle' => 'editor_style_handles',
  387. 'style' => 'style_handles',
  388. );
  389. foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
  390. if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
  391. $styles = $metadata[ $metadata_field_name ];
  392. $processed_styles = array();
  393. if ( is_array( $styles ) ) {
  394. for ( $index = 0; $index < count( $styles ); $index++ ) {
  395. $result = register_block_style_handle(
  396. $metadata,
  397. $metadata_field_name,
  398. $index
  399. );
  400. if ( $result ) {
  401. $processed_styles[] = $result;
  402. }
  403. }
  404. } else {
  405. $result = register_block_style_handle(
  406. $metadata,
  407. $metadata_field_name
  408. );
  409. if ( $result ) {
  410. $processed_styles[] = $result;
  411. }
  412. }
  413. $settings[ $settings_field_name ] = $processed_styles;
  414. }
  415. }
  416. if ( ! empty( $metadata['render'] ) ) {
  417. $template_path = wp_normalize_path(
  418. realpath(
  419. dirname( $metadata['file'] ) . '/' .
  420. remove_block_asset_path_prefix( $metadata['render'] )
  421. )
  422. );
  423. if ( $template_path ) {
  424. /**
  425. * Renders the block on the server.
  426. *
  427. * @since 6.1.0
  428. *
  429. * @param array $attributes Block attributes.
  430. * @param string $content Block default content.
  431. * @param WP_Block $block Block instance.
  432. *
  433. * @return string Returns the block content.
  434. */
  435. $settings['render_callback'] = function( $attributes, $content, $block ) use ( $template_path ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
  436. ob_start();
  437. require $template_path;
  438. return ob_get_clean();
  439. };
  440. }
  441. }
  442. /**
  443. * Filters the settings determined from the block type metadata.
  444. *
  445. * @since 5.7.0
  446. *
  447. * @param array $settings Array of determined settings for registering a block type.
  448. * @param array $metadata Metadata provided for registering a block type.
  449. */
  450. $settings = apply_filters(
  451. 'block_type_metadata_settings',
  452. array_merge(
  453. $settings,
  454. $args
  455. ),
  456. $metadata
  457. );
  458. return WP_Block_Type_Registry::get_instance()->register(
  459. $metadata['name'],
  460. $settings
  461. );
  462. }
  463. /**
  464. * Registers a block type. The recommended way is to register a block type using
  465. * the metadata stored in the `block.json` file.
  466. *
  467. * @since 5.0.0
  468. * @since 5.8.0 First parameter now accepts a path to the `block.json` file.
  469. *
  470. * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
  471. * a path to the JSON file with metadata definition for the block,
  472. * or a path to the folder where the `block.json` file is located,
  473. * or a complete WP_Block_Type instance.
  474. * In case a WP_Block_Type is provided, the $args parameter will be ignored.
  475. * @param array $args Optional. Array of block type arguments. Accepts any public property
  476. * of `WP_Block_Type`. See WP_Block_Type::__construct() for information
  477. * on accepted arguments. Default empty array.
  478. *
  479. * @return WP_Block_Type|false The registered block type on success, or false on failure.
  480. */
  481. function register_block_type( $block_type, $args = array() ) {
  482. if ( is_string( $block_type ) && file_exists( $block_type ) ) {
  483. return register_block_type_from_metadata( $block_type, $args );
  484. }
  485. return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
  486. }
  487. /**
  488. * Unregisters a block type.
  489. *
  490. * @since 5.0.0
  491. *
  492. * @param string|WP_Block_Type $name Block type name including namespace, or alternatively
  493. * a complete WP_Block_Type instance.
  494. * @return WP_Block_Type|false The unregistered block type on success, or false on failure.
  495. */
  496. function unregister_block_type( $name ) {
  497. return WP_Block_Type_Registry::get_instance()->unregister( $name );
  498. }
  499. /**
  500. * Determines whether a post or content string has blocks.
  501. *
  502. * This test optimizes for performance rather than strict accuracy, detecting
  503. * the pattern of a block but not validating its structure. For strict accuracy,
  504. * you should use the block parser on post content.
  505. *
  506. * @since 5.0.0
  507. *
  508. * @see parse_blocks()
  509. *
  510. * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
  511. * Defaults to global $post.
  512. * @return bool Whether the post has blocks.
  513. */
  514. function has_blocks( $post = null ) {
  515. if ( ! is_string( $post ) ) {
  516. $wp_post = get_post( $post );
  517. if ( ! $wp_post instanceof WP_Post ) {
  518. return false;
  519. }
  520. $post = $wp_post->post_content;
  521. }
  522. return false !== strpos( (string) $post, '<!-- wp:' );
  523. }
  524. /**
  525. * Determines whether a $post or a string contains a specific block type.
  526. *
  527. * This test optimizes for performance rather than strict accuracy, detecting
  528. * whether the block type exists but not validating its structure and not checking
  529. * reusable blocks. For strict accuracy, you should use the block parser on post content.
  530. *
  531. * @since 5.0.0
  532. *
  533. * @see parse_blocks()
  534. *
  535. * @param string $block_name Full block type to look for.
  536. * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
  537. * Defaults to global $post.
  538. * @return bool Whether the post content contains the specified block.
  539. */
  540. function has_block( $block_name, $post = null ) {
  541. if ( ! has_blocks( $post ) ) {
  542. return false;
  543. }
  544. if ( ! is_string( $post ) ) {
  545. $wp_post = get_post( $post );
  546. if ( $wp_post instanceof WP_Post ) {
  547. $post = $wp_post->post_content;
  548. }
  549. }
  550. /*
  551. * Normalize block name to include namespace, if provided as non-namespaced.
  552. * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
  553. * their serialized names.
  554. */
  555. if ( false === strpos( $block_name, '/' ) ) {
  556. $block_name = 'core/' . $block_name;
  557. }
  558. // Test for existence of block by its fully qualified name.
  559. $has_block = false !== strpos( $post, '<!-- wp:' . $block_name . ' ' );
  560. if ( ! $has_block ) {
  561. /*
  562. * If the given block name would serialize to a different name, test for
  563. * existence by the serialized form.
  564. */
  565. $serialized_block_name = strip_core_block_namespace( $block_name );
  566. if ( $serialized_block_name !== $block_name ) {
  567. $has_block = false !== strpos( $post, '<!-- wp:' . $serialized_block_name . ' ' );
  568. }
  569. }
  570. return $has_block;
  571. }
  572. /**
  573. * Returns an array of the names of all registered dynamic block types.
  574. *
  575. * @since 5.0.0
  576. *
  577. * @return string[] Array of dynamic block names.
  578. */
  579. function get_dynamic_block_names() {
  580. $dynamic_block_names = array();
  581. $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
  582. foreach ( $block_types as $block_type ) {
  583. if ( $block_type->is_dynamic() ) {
  584. $dynamic_block_names[] = $block_type->name;
  585. }
  586. }
  587. return $dynamic_block_names;
  588. }
  589. /**
  590. * Given an array of attributes, returns a string in the serialized attributes
  591. * format prepared for post content.
  592. *
  593. * The serialized result is a JSON-encoded string, with unicode escape sequence
  594. * substitution for characters which might otherwise interfere with embedding
  595. * the result in an HTML comment.
  596. *
  597. * This function must produce output that remains in sync with the output of
  598. * the serializeAttributes JavaScript function in the block editor in order
  599. * to ensure consistent operation between PHP and JavaScript.
  600. *
  601. * @since 5.3.1
  602. *
  603. * @param array $block_attributes Attributes object.
  604. * @return string Serialized attributes.
  605. */
  606. function serialize_block_attributes( $block_attributes ) {
  607. $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
  608. $encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes );
  609. $encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes );
  610. $encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes );
  611. $encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes );
  612. // Regex: /\\"/
  613. $encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes );
  614. return $encoded_attributes;
  615. }
  616. /**
  617. * Returns the block name to use for serialization. This will remove the default
  618. * "core/" namespace from a block name.
  619. *
  620. * @since 5.3.1
  621. *
  622. * @param string|null $block_name Optional. Original block name. Null if the block name is unknown,
  623. * e.g. Classic blocks have their name set to null. Default null.
  624. * @return string Block name to use for serialization.
  625. */
  626. function strip_core_block_namespace( $block_name = null ) {
  627. if ( is_string( $block_name ) && 0 === strpos( $block_name, 'core/' ) ) {
  628. return substr( $block_name, 5 );
  629. }
  630. return $block_name;
  631. }
  632. /**
  633. * Returns the content of a block, including comment delimiters.
  634. *
  635. * @since 5.3.1
  636. *
  637. * @param string|null $block_name Block name. Null if the block name is unknown,
  638. * e.g. Classic blocks have their name set to null.
  639. * @param array $block_attributes Block attributes.
  640. * @param string $block_content Block save content.
  641. * @return string Comment-delimited block content.
  642. */
  643. function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) {
  644. if ( is_null( $block_name ) ) {
  645. return $block_content;
  646. }
  647. $serialized_block_name = strip_core_block_namespace( $block_name );
  648. $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' ';
  649. if ( empty( $block_content ) ) {
  650. return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes );
  651. }
  652. return sprintf(
  653. '<!-- wp:%s %s-->%s<!-- /wp:%s -->',
  654. $serialized_block_name,
  655. $serialized_attributes,
  656. $block_content,
  657. $serialized_block_name
  658. );
  659. }
  660. /**
  661. * Returns the content of a block, including comment delimiters, serializing all
  662. * attributes from the given parsed block.
  663. *
  664. * This should be used when preparing a block to be saved to post content.
  665. * Prefer `render_block` when preparing a block for display. Unlike
  666. * `render_block`, this does not evaluate a block's `render_callback`, and will
  667. * instead preserve the markup as parsed.
  668. *
  669. * @since 5.3.1
  670. *
  671. * @param array $block A representative array of a single parsed block object. See WP_Block_Parser_Block.
  672. * @return string String of rendered HTML.
  673. */
  674. function serialize_block( $block ) {
  675. $block_content = '';
  676. $index = 0;
  677. foreach ( $block['innerContent'] as $chunk ) {
  678. $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] );
  679. }
  680. if ( ! is_array( $block['attrs'] ) ) {
  681. $block['attrs'] = array();
  682. }
  683. return get_comment_delimited_block_content(
  684. $block['blockName'],
  685. $block['attrs'],
  686. $block_content
  687. );
  688. }
  689. /**
  690. * Returns a joined string of the aggregate serialization of the given
  691. * parsed blocks.
  692. *
  693. * @since 5.3.1
  694. *
  695. * @param array[] $blocks An array of representative arrays of parsed block objects. See serialize_block().
  696. * @return string String of rendered HTML.
  697. */
  698. function serialize_blocks( $blocks ) {
  699. return implode( '', array_map( 'serialize_block', $blocks ) );
  700. }
  701. /**
  702. * Filters and sanitizes block content to remove non-allowable HTML
  703. * from parsed block attribute values.
  704. *
  705. * @since 5.3.1
  706. *
  707. * @param string $text Text that may contain block content.
  708. * @param array[]|string $allowed_html Optional. An array of allowed HTML elements and attributes,
  709. * or a context name such as 'post'. See wp_kses_allowed_html()
  710. * for the list of accepted context names. Default 'post'.
  711. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
  712. * Defaults to the result of wp_allowed_protocols().
  713. * @return string The filtered and sanitized content result.
  714. */
  715. function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) {
  716. $result = '';
  717. $blocks = parse_blocks( $text );
  718. foreach ( $blocks as $block ) {
  719. $block = filter_block_kses( $block, $allowed_html, $allowed_protocols );
  720. $result .= serialize_block( $block );
  721. }
  722. return $result;
  723. }
  724. /**
  725. * Filters and sanitizes a parsed block to remove non-allowable HTML
  726. * from block attribute values.
  727. *
  728. * @since 5.3.1
  729. *
  730. * @param WP_Block_Parser_Block $block The parsed block object.
  731. * @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
  732. * or a context name such as 'post'. See wp_kses_allowed_html()
  733. * for the list of accepted context names.
  734. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
  735. * Defaults to the result of wp_allowed_protocols().
  736. * @return array The filtered and sanitized block object result.
  737. */
  738. function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) {
  739. $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols );
  740. if ( is_array( $block['innerBlocks'] ) ) {
  741. foreach ( $block['innerBlocks'] as $i => $inner_block ) {
  742. $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols );
  743. }
  744. }
  745. return $block;
  746. }
  747. /**
  748. * Filters and sanitizes a parsed block attribute value to remove
  749. * non-allowable HTML.
  750. *
  751. * @since 5.3.1
  752. *
  753. * @param string[]|string $value The attribute value to filter.
  754. * @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
  755. * or a context name such as 'post'. See wp_kses_allowed_html()
  756. * for the list of accepted context names.
  757. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
  758. * Defaults to the result of wp_allowed_protocols().
  759. * @return string[]|string The filtered and sanitized result.
  760. */
  761. function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) {
  762. if ( is_array( $value ) ) {
  763. foreach ( $value as $key => $inner_value ) {
  764. $filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols );
  765. $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols );
  766. if ( $filtered_key !== $key ) {
  767. unset( $value[ $key ] );
  768. }
  769. $value[ $filtered_key ] = $filtered_value;
  770. }
  771. } elseif ( is_string( $value ) ) {
  772. return wp_kses( $value, $allowed_html, $allowed_protocols );
  773. }
  774. return $value;
  775. }
  776. /**
  777. * Parses blocks out of a content string, and renders those appropriate for the excerpt.
  778. *
  779. * As the excerpt should be a small string of text relevant to the full post content,
  780. * this function renders the blocks that are most likely to contain such text.
  781. *
  782. * @since 5.0.0
  783. *
  784. * @param string $content The content to parse.
  785. * @return string The parsed and filtered content.
  786. */
  787. function excerpt_remove_blocks( $content ) {
  788. $allowed_inner_blocks = array(
  789. // Classic blocks have their blockName set to null.
  790. null,
  791. 'core/freeform',
  792. 'core/heading',
  793. 'core/html',
  794. 'core/list',
  795. 'core/media-text',
  796. 'core/paragraph',
  797. 'core/preformatted',
  798. 'core/pullquote',
  799. 'core/quote',
  800. 'core/table',
  801. 'core/verse',
  802. );
  803. $allowed_wrapper_blocks = array(
  804. 'core/columns',
  805. 'core/column',
  806. 'core/group',
  807. );
  808. /**
  809. * Filters the list of blocks that can be used as wrapper blocks, allowing
  810. * excerpts to be generated from the `innerBlocks` of these wrappers.
  811. *
  812. * @since 5.8.0
  813. *
  814. * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks.
  815. */
  816. $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks );
  817. $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks );
  818. /**
  819. * Filters the list of blocks that can contribute to the excerpt.
  820. *
  821. * If a dynamic block is added to this list, it must not generate another
  822. * excerpt, as this will cause an infinite loop to occur.
  823. *
  824. * @since 5.0.0
  825. *
  826. * @param string[] $allowed_blocks The list of names of allowed blocks.
  827. */
  828. $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks );
  829. $blocks = parse_blocks( $content );
  830. $output = '';
  831. foreach ( $blocks as $block ) {
  832. if ( in_array( $block['blockName'], $allowed_blocks, true ) ) {
  833. if ( ! empty( $block['innerBlocks'] ) ) {
  834. if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) {
  835. $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks );
  836. continue;
  837. }
  838. // Skip the block if it has disallowed or nested inner blocks.
  839. foreach ( $block['innerBlocks'] as $inner_block ) {
  840. if (
  841. ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) ||
  842. ! empty( $inner_block['innerBlocks'] )
  843. ) {
  844. continue 2;
  845. }
  846. }
  847. }
  848. $output .= render_block( $block );
  849. }
  850. }
  851. return $output;
  852. }
  853. /**
  854. * Renders inner blocks from the allowed wrapper blocks
  855. * for generating an excerpt.
  856. *
  857. * @since 5.8.0
  858. * @access private
  859. *
  860. * @param array $parsed_block The parsed block.
  861. * @param array $allowed_blocks The list of allowed inner blocks.
  862. * @return string The rendered inner blocks.
  863. */
  864. function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) {
  865. $output = '';
  866. foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
  867. if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) {
  868. continue;
  869. }
  870. if ( empty( $inner_block['innerBlocks'] ) ) {
  871. $output .= render_block( $inner_block );
  872. } else {
  873. $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks );
  874. }
  875. }
  876. return $output;
  877. }
  878. /**
  879. * Renders a single block into a HTML string.
  880. *
  881. * @since 5.0.0
  882. *
  883. * @global WP_Post $post The post to edit.
  884. *
  885. * @param array $parsed_block A single parsed block object.
  886. * @return string String of rendered HTML.
  887. */
  888. function render_block( $parsed_block ) {
  889. global $post;
  890. $parent_block = null;
  891. /**
  892. * Allows render_block() to be short-circuited, by returning a non-null value.
  893. *
  894. * @since 5.1.0
  895. * @since 5.9.0 The `$parent_block` parameter was added.
  896. *
  897. * @param string|null $pre_render The pre-rendered content. Default null.
  898. * @param array $parsed_block The block being rendered.
  899. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
  900. */
  901. $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );
  902. if ( ! is_null( $pre_render ) ) {
  903. return $pre_render;
  904. }
  905. $source_block = $parsed_block;
  906. /**
  907. * Filters the block being rendered in render_block(), before it's processed.
  908. *
  909. * @since 5.1.0
  910. * @since 5.9.0 The `$parent_block` parameter was added.
  911. *
  912. * @param array $parsed_block The block being rendered.
  913. * @param array $source_block An un-modified copy of $parsed_block, as it appeared in the source content.
  914. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
  915. */
  916. $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block );
  917. $context = array();
  918. if ( $post instanceof WP_Post ) {
  919. $context['postId'] = $post->ID;
  920. /*
  921. * The `postType` context is largely unnecessary server-side, since the ID
  922. * is usually sufficient on its own. That being said, since a block's
  923. * manifest is expected to be shared between the server and the client,
  924. * it should be included to consistently fulfill the expectation.
  925. */
  926. $context['postType'] = $post->post_type;
  927. }
  928. /**
  929. * Filters the default context provided to a rendered block.
  930. *
  931. * @since 5.5.0
  932. * @since 5.9.0 The `$parent_block` parameter was added.
  933. *
  934. * @param array $context Default context.
  935. * @param array $parsed_block Block being rendered, filtered by `render_block_data`.
  936. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block.
  937. */
  938. $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block );
  939. $block = new WP_Block( $parsed_block, $context );
  940. return $block->render();
  941. }
  942. /**
  943. * Parses blocks out of a content string.
  944. *
  945. * @since 5.0.0
  946. *
  947. * @param string $content Post content.
  948. * @return array[] Array of parsed block objects.
  949. */
  950. function parse_blocks( $content ) {
  951. /**
  952. * Filter to allow plugins to replace the server-side block parser.
  953. *
  954. * @since 5.0.0
  955. *
  956. * @param string $parser_class Name of block parser class.
  957. */
  958. $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
  959. $parser = new $parser_class();
  960. return $parser->parse( $content );
  961. }
  962. /**
  963. * Parses dynamic blocks out of `post_content` and re-renders them.
  964. *
  965. * @since 5.0.0
  966. *
  967. * @param string $content Post content.
  968. * @return string Updated post content.
  969. */
  970. function do_blocks( $content ) {
  971. $blocks = parse_blocks( $content );
  972. $output = '';
  973. foreach ( $blocks as $block ) {
  974. $output .= render_block( $block );
  975. }
  976. // If there are blocks in this content, we shouldn't run wpautop() on it later.
  977. $priority = has_filter( 'the_content', 'wpautop' );
  978. if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
  979. remove_filter( 'the_content', 'wpautop', $priority );
  980. add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
  981. }
  982. return $output;
  983. }
  984. /**
  985. * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
  986. * for subsequent `the_content` usage.
  987. *
  988. * @since 5.0.0
  989. * @access private
  990. *
  991. * @param string $content The post content running through this filter.
  992. * @return string The unmodified content.
  993. */
  994. function _restore_wpautop_hook( $content ) {
  995. $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
  996. add_filter( 'the_content', 'wpautop', $current_priority - 1 );
  997. remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
  998. return $content;
  999. }
  1000. /**
  1001. * Returns the current version of the block format that the content string is using.
  1002. *
  1003. * If the string doesn't contain blocks, it returns 0.
  1004. *
  1005. * @since 5.0.0
  1006. *
  1007. * @param string $content Content to test.
  1008. * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
  1009. */
  1010. function block_version( $content ) {
  1011. return has_blocks( $content ) ? 1 : 0;
  1012. }
  1013. /**
  1014. * Registers a new block style.
  1015. *
  1016. * @since 5.3.0
  1017. *
  1018. * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/
  1019. *
  1020. * @param string $block_name Block type name including namespace.
  1021. * @param array $style_properties Array containing the properties of the style name,
  1022. * label, style (name of the stylesheet to be enqueued),
  1023. * inline_style (string containing the CSS to be added).
  1024. * @return bool True if the block style was registered with success and false otherwise.
  1025. */
  1026. function register_block_style( $block_name, $style_properties ) {
  1027. return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
  1028. }
  1029. /**
  1030. * Unregisters a block style.
  1031. *
  1032. * @since 5.3.0
  1033. *
  1034. * @param string $block_name Block type name including namespace.
  1035. * @param string $block_style_name Block style name.
  1036. * @return bool True if the block style was unregistered with success and false otherwise.
  1037. */
  1038. function unregister_block_style( $block_name, $block_style_name ) {
  1039. return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
  1040. }
  1041. /**
  1042. * Checks whether the current block type supports the feature requested.
  1043. *
  1044. * @since 5.8.0
  1045. *
  1046. * @param WP_Block_Type $block_type Block type to check for support.
  1047. * @param array $feature Path to a specific feature to check support for.
  1048. * @param mixed $default Optional. Fallback value for feature support. Default false.
  1049. * @return bool Whether the feature is supported.
  1050. */
  1051. function block_has_support( $block_type, $feature, $default = false ) {
  1052. $block_support = $default;
  1053. if ( $block_type && property_exists( $block_type, 'supports' ) ) {
  1054. $block_support = _wp_array_get( $block_type->supports, $feature, $default );
  1055. }
  1056. return true === $block_support || is_array( $block_support );
  1057. }
  1058. /**
  1059. * Converts typography keys declared under `supports.*` to `supports.typography.*`.
  1060. *
  1061. * Displays a `_doing_it_wrong()` notice when a block using the older format is detected.
  1062. *
  1063. * @since 5.8.0
  1064. *
  1065. * @param array $metadata Metadata for registering a block type.
  1066. * @return array Filtered metadata for registering a block type.
  1067. */
  1068. function wp_migrate_old_typography_shape( $metadata ) {
  1069. if ( ! isset( $metadata['supports'] ) ) {
  1070. return $metadata;
  1071. }
  1072. $typography_keys = array(
  1073. '__experimentalFontFamily',
  1074. '__experimentalFontStyle',
  1075. '__experimentalFontWeight',
  1076. '__experimentalLetterSpacing',
  1077. '__experimentalTextDecoration',
  1078. '__experimentalTextTransform',
  1079. 'fontSize',
  1080. 'lineHeight',
  1081. );
  1082. foreach ( $typography_keys as $typography_key ) {
  1083. $support_for_key = _wp_array_get( $metadata['supports'], array( $typography_key ), null );
  1084. if ( null !== $support_for_key ) {
  1085. _doing_it_wrong(
  1086. 'register_block_type_from_metadata()',
  1087. sprintf(
  1088. /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */
  1089. __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ),
  1090. $metadata['name'],
  1091. "<code>$typography_key</code>",
  1092. '<code>block.json</code>',
  1093. "<code>supports.$typography_key</code>",
  1094. "<code>supports.typography.$typography_key</code>"
  1095. ),
  1096. '5.8.0'
  1097. );
  1098. _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key );
  1099. unset( $metadata['supports'][ $typography_key ] );
  1100. }
  1101. }
  1102. return $metadata;
  1103. }
  1104. /**
  1105. * Helper function that constructs a WP_Query args array from
  1106. * a `Query` block properties.
  1107. *
  1108. * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks.
  1109. *
  1110. * @since 5.8.0
  1111. * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query.
  1112. *
  1113. * @param WP_Block $block Block instance.
  1114. * @param int $page Current query's page.
  1115. *
  1116. * @return array Returns the constructed WP_Query arguments.
  1117. */
  1118. function build_query_vars_from_query_block( $block, $page ) {
  1119. $query = array(
  1120. 'post_type' => 'post',
  1121. 'order' => 'DESC',
  1122. 'orderby' => 'date',
  1123. 'post__not_in' => array(),
  1124. );
  1125. if ( isset( $block->context['query'] ) ) {
  1126. if ( ! empty( $block->context['query']['postType'] ) ) {
  1127. $post_type_param = $block->context['query']['postType'];
  1128. if ( is_post_type_viewable( $post_type_param ) ) {
  1129. $query['post_type'] = $post_type_param;
  1130. }
  1131. }
  1132. if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
  1133. $sticky = get_option( 'sticky_posts' );
  1134. if ( 'only' === $block->context['query']['sticky'] ) {
  1135. $query['post__in'] = $sticky;
  1136. } else {
  1137. $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
  1138. }
  1139. }
  1140. if ( ! empty( $block->context['query']['exclude'] ) ) {
  1141. $excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] );
  1142. $excluded_post_ids = array_filter( $excluded_post_ids );
  1143. $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
  1144. }
  1145. if (
  1146. isset( $block->context['query']['perPage'] ) &&
  1147. is_numeric( $block->context['query']['perPage'] )
  1148. ) {
  1149. $per_page = absint( $block->context['query']['perPage'] );
  1150. $offset = 0;
  1151. if (
  1152. isset( $block->context['query']['offset'] ) &&
  1153. is_numeric( $block->context['query']['offset'] )
  1154. ) {
  1155. $offset = absint( $block->context['query']['offset'] );
  1156. }
  1157. $query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset;
  1158. $query['posts_per_page'] = $per_page;
  1159. }
  1160. // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility.
  1161. if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) {
  1162. $tax_query = array();
  1163. if ( ! empty( $block->context['query']['categoryIds'] ) ) {
  1164. $tax_query[] = array(
  1165. 'taxonomy' => 'category',
  1166. 'terms' => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ),
  1167. 'include_children' => false,
  1168. );
  1169. }
  1170. if ( ! empty( $block->context['query']['tagIds'] ) ) {
  1171. $tax_query[] = array(
  1172. 'taxonomy' => 'post_tag',
  1173. 'terms' => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ),
  1174. 'include_children' => false,
  1175. );
  1176. }
  1177. $query['tax_query'] = $tax_query;
  1178. }
  1179. if ( ! empty( $block->context['query']['taxQuery'] ) ) {
  1180. $query['tax_query'] = array();
  1181. foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) {
  1182. if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) {
  1183. $query['tax_query'][] = array(
  1184. 'taxonomy' => $taxonomy,
  1185. 'terms' => array_filter( array_map( 'intval', $terms ) ),
  1186. 'include_children' => false,
  1187. );
  1188. }
  1189. }
  1190. }
  1191. if (
  1192. isset( $block->context['query']['order'] ) &&
  1193. in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
  1194. ) {
  1195. $query['order'] = strtoupper( $block->context['query']['order'] );
  1196. }
  1197. if ( isset( $block->context['query']['orderBy'] ) ) {
  1198. $query['orderby'] = $block->context['query']['orderBy'];
  1199. }
  1200. if (
  1201. isset( $block->context['query']['author'] ) &&
  1202. (int) $block->context['query']['author'] > 0
  1203. ) {
  1204. $query['author'] = (int) $block->context['query']['author'];
  1205. }
  1206. if ( ! empty( $block->context['query']['search'] ) ) {
  1207. $query['s'] = $block->context['query']['search'];
  1208. }
  1209. if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) {
  1210. $query['post_parent__in'] = array_filter( array_map( 'intval', $block->context['query']['parents'] ) );
  1211. }
  1212. }
  1213. /**
  1214. * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block.
  1215. *
  1216. * Anything to this filter should be compatible with the `WP_Query` API to form
  1217. * the query context which will be passed down to the Query Loop Block's children.
  1218. * This can help, for example, to include additional settings or meta queries not
  1219. * directly supported by the core Query Loop Block, and extend its capabilities.
  1220. *
  1221. * Please note that this will only influence the query that will be rendered on the
  1222. * front-end. The editor preview is not affected by this filter. Also, worth noting
  1223. * that the editor preview uses the REST API, so, ideally, one should aim to provide
  1224. * attributes which are also compatible with the REST API, in order to be able to
  1225. * implement identical queries on both sides.
  1226. *
  1227. * @since 6.1.0
  1228. *
  1229. * @param array $query Array containing parameters for `WP_Query` as parsed by the block context.
  1230. * @param WP_Block $block Block instance.
  1231. * @param int $page Current query's page.
  1232. */
  1233. return apply_filters( 'query_loop_block_query_vars', $query, $block, $page );
  1234. }
  1235. /**
  1236. * Helper function that returns the proper pagination arrow HTML for
  1237. * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based
  1238. * on the provided `paginationArrow` from `QueryPagination` context.
  1239. *
  1240. * It's used in QueryPaginationNext and QueryPaginationPrevious blocks.
  1241. *
  1242. * @since 5.9.0
  1243. *
  1244. * @param WP_Block $block Block instance.
  1245. * @param bool $is_next Flag for handling `next/previous` blocks.
  1246. * @return string|null The pagination arrow HTML or null if there is none.
  1247. */
  1248. function get_query_pagination_arrow( $block, $is_next ) {
  1249. $arrow_map = array(
  1250. 'none' => '',
  1251. 'arrow' => array(
  1252. 'next' => '→',
  1253. 'previous' => '←',
  1254. ),
  1255. 'chevron' => array(
  1256. 'next' => '»',
  1257. 'previous' => '«',
  1258. ),
  1259. );
  1260. if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) {
  1261. $pagination_type = $is_next ? 'next' : 'previous';
  1262. $arrow_attribute = $block->context['paginationArrow'];
  1263. $arrow = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ];
  1264. $arrow_classes = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
  1265. return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
  1266. }
  1267. return null;
  1268. }
  1269. /**
  1270. * Helper function that constructs a comment query vars array from the passed
  1271. * block properties.
  1272. *
  1273. * It's used with the Comment Query Loop inner blocks.
  1274. *
  1275. * @since 6.0.0
  1276. *
  1277. * @param WP_Block $block Block instance.
  1278. * @return array Returns the comment query parameters to use with the
  1279. * WP_Comment_Query constructor.
  1280. */
  1281. function build_comment_query_vars_from_block( $block ) {
  1282. $comment_args = array(
  1283. 'orderby' => 'comment_date_gmt',
  1284. 'order' => 'ASC',
  1285. 'status' => 'approve',
  1286. 'no_found_rows' => false,
  1287. );
  1288. if ( is_user_logged_in() ) {
  1289. $comment_args['include_unapproved'] = array( get_current_user_id() );
  1290. } else {
  1291. $unapproved_email = wp_get_unapproved_comment_author_email();
  1292. if ( $unapproved_email ) {
  1293. $comment_args['include_unapproved'] = array( $unapproved_email );
  1294. }
  1295. }
  1296. if ( ! empty( $block->context['postId'] ) ) {
  1297. $comment_args['post_id'] = (int) $block->context['postId'];
  1298. }
  1299. if ( get_option( 'thread_comments' ) ) {
  1300. $comment_args['hierarchical'] = 'threaded';
  1301. } else {
  1302. $comment_args['hierarchical'] = false;
  1303. }
  1304. if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) {
  1305. $per_page = get_option( 'comments_per_page' );
  1306. $default_page = get_option( 'default_comments_page' );
  1307. if ( $per_page > 0 ) {
  1308. $comment_args['number'] = $per_page;
  1309. $page = (int) get_query_var( 'cpage' );
  1310. if ( $page ) {
  1311. $comment_args['paged'] = $page;
  1312. } elseif ( 'oldest' === $default_page ) {
  1313. $comment_args['paged'] = 1;
  1314. } elseif ( 'newest' === $default_page ) {
  1315. $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages;
  1316. if ( 0 !== $max_num_pages ) {
  1317. $comment_args['paged'] = $max_num_pages;
  1318. }
  1319. }
  1320. // Set the `cpage` query var to ensure the previous and next pagination links are correct
  1321. // when inheriting the Discussion Settings.
  1322. if ( 0 === $page && isset( $comment_args['paged'] ) && $comment_args['paged'] > 0 ) {
  1323. set_query_var( 'cpage', $comment_args['paged'] );
  1324. }
  1325. }
  1326. }
  1327. return $comment_args;
  1328. }
  1329. /**
  1330. * Helper function that returns the proper pagination arrow HTML for
  1331. * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the
  1332. * provided `paginationArrow` from `CommentsPagination` context.
  1333. *
  1334. * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks.
  1335. *
  1336. * @since 6.0.0
  1337. *
  1338. * @param WP_Block $block Block instance.
  1339. * @param string $pagination_type Optional. Type of the arrow we will be rendering.
  1340. * Accepts 'next' or 'previous'. Default 'next'.
  1341. * @return string|null The pagination arrow HTML or null if there is none.
  1342. */
  1343. function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) {
  1344. $arrow_map = array(
  1345. 'none' => '',
  1346. 'arrow' => array(
  1347. 'next' => '→',
  1348. 'previous' => '←',
  1349. ),
  1350. 'chevron' => array(
  1351. 'next' => '»',
  1352. 'previous' => '«',
  1353. ),
  1354. );
  1355. if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) {
  1356. $arrow_attribute = $block->context['comments/paginationArrow'];
  1357. $arrow = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ];
  1358. $arrow_classes = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
  1359. return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>";
  1360. }
  1361. return null;
  1362. }