ShortcodesBlockConversionService.php
2 years ago
ShortcodesService.php
3 years ago
ShortcodesServiceProvider.php
2 years ago
ShortcodesService.php
71 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\WordPress\Shortcodes; |
| 4 | |
| 5 | /** |
| 6 | * The shortcodes service. |
| 7 | */ |
| 8 | class ShortcodesService { |
| 9 | /** |
| 10 | * Convert the block |
| 11 | * |
| 12 | * @param string $name Block name. |
| 13 | * @param string $block Block class. |
| 14 | * @param array $defaults Default attributes. |
| 15 | * |
| 16 | * @return string |
| 17 | */ |
| 18 | public function registerBlockShortcode( $name, $class, $defaults = [] ) { |
| 19 | add_shortcode( |
| 20 | $name, |
| 21 | function( $attributes, $content ) use ( $name, $class, $defaults ) { |
| 22 | return ( new ShortcodesBlockConversionService( $attributes, $content ) )->convert( |
| 23 | $name, |
| 24 | $class, |
| 25 | $defaults |
| 26 | ); |
| 27 | }, |
| 28 | 10, |
| 29 | 2 |
| 30 | ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Register shortcode by name |
| 35 | * |
| 36 | * @param string $name Name of the shortcode. |
| 37 | * @param string $block_name The registered block name. |
| 38 | * @param array $defaults Default attributes. |
| 39 | * |
| 40 | * @return void |
| 41 | */ |
| 42 | public function registerBlockShortcodeByName( $name, $block_name, $defaults = [] ) { |
| 43 | add_shortcode( |
| 44 | $name, |
| 45 | function( $attributes, $content ) use ( $name, $block_name, $defaults ) { |
| 46 | // convert comma separated attributes to array. |
| 47 | foreach ( $attributes as $key => $value ) { |
| 48 | if ( strpos( $value, ',' ) !== 0 && is_array( $defaults[ $key ] ) ) { |
| 49 | $attributes[ $key ] = explode( ',', $value ); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | $shortcode_attrs = shortcode_atts( |
| 54 | $defaults, |
| 55 | $attributes, |
| 56 | $name |
| 57 | ); |
| 58 | |
| 59 | $block = new \WP_Block( |
| 60 | [ |
| 61 | 'blockName' => $block_name, |
| 62 | 'attrs' => $shortcode_attrs, |
| 63 | 'innerContent' => do_shortcode( $content ), |
| 64 | ] |
| 65 | ); |
| 66 | return $block->render(); |
| 67 | } |
| 68 | ); |
| 69 | } |
| 70 | } |
| 71 |