Ei kuvausta

class-wc-blocks-utils.php 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Blocks Utils
  4. *
  5. * Used by core components that need to work with blocks.
  6. *
  7. * @package WooCommerce\Blocks\Utils
  8. * @version 5.0.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Blocks Utility class.
  13. */
  14. class WC_Blocks_Utils {
  15. /**
  16. * Get blocks from a woocommerce page.
  17. *
  18. * @param string $woo_page_name A woocommerce page e.g. `checkout` or `cart`.
  19. * @return array Array of blocks as returned by parse_blocks().
  20. */
  21. private static function get_all_blocks_from_page( $woo_page_name ) {
  22. $page_id = wc_get_page_id( $woo_page_name );
  23. $page = get_post( $page_id );
  24. if ( ! $page ) {
  25. return array();
  26. }
  27. $blocks = parse_blocks( $page->post_content );
  28. if ( ! $blocks ) {
  29. return array();
  30. }
  31. return $blocks;
  32. }
  33. /**
  34. * Get all instances of the specified block on a specific woo page
  35. * (e.g. `cart` or `checkout` page).
  36. *
  37. * @param string $block_name The name (id) of a block, e.g. `woocommerce/cart`.
  38. * @param string $woo_page_name The woo page to search, e.g. `cart`.
  39. * @return array Array of blocks as returned by parse_blocks().
  40. */
  41. public static function get_blocks_from_page( $block_name, $woo_page_name ) {
  42. $page_blocks = self::get_all_blocks_from_page( $woo_page_name );
  43. // Get any instances of the specified block.
  44. return array_values(
  45. array_filter(
  46. $page_blocks,
  47. function ( $block ) use ( $block_name ) {
  48. return ( $block_name === $block['blockName'] );
  49. }
  50. )
  51. );
  52. }
  53. /**
  54. * Check if a given page contains a particular block.
  55. *
  56. * @param int|WP_Post $page Page post ID or post object.
  57. * @param string $block_name The name (id) of a block, e.g. `woocommerce/cart`.
  58. * @return bool Boolean value if the page contains the block or not. Null in case the page does not exist.
  59. */
  60. public static function has_block_in_page( $page, $block_name ) {
  61. $page_to_check = get_post( $page );
  62. if ( null === $page_to_check ) {
  63. return false;
  64. }
  65. $blocks = parse_blocks( $page_to_check->post_content );
  66. foreach ( $blocks as $block ) {
  67. if ( $block_name === $block['blockName'] ) {
  68. return true;
  69. }
  70. }
  71. return false;
  72. }
  73. }