AdminMenuPageService.php
3 months ago
AdminMenuPageServiceProvider.php
9 months ago
AdminToolbarService.php
9 months ago
ProductCollectionsMenuService.php
4 months ago
ProductCollectionsMenuService.php
55 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\WordPress\Admin\Menus; |
| 4 | |
| 5 | use SureCart\Models\ProductCollection; |
| 6 | |
| 7 | /** |
| 8 | * Service for product collection pages in WordPress menu related functions. |
| 9 | */ |
| 10 | class ProductCollectionsMenuService { |
| 11 | /** |
| 12 | * Bootstrap any actions. |
| 13 | * |
| 14 | * @return void |
| 15 | */ |
| 16 | public function bootstrap(): void { |
| 17 | add_filter( 'render_block', [ $this, 'filterMenuBlockLinkHref' ], 10, 2 ); |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * If the menu item is a collection page, add the collection slug to the menu item.. |
| 22 | * |
| 23 | * @param string $content Block content. |
| 24 | * @param array $block_data Block data. |
| 25 | * |
| 26 | * @return array |
| 27 | */ |
| 28 | public function filterMenuBlockLinkHref( $content, $block_data ) { |
| 29 | // not a navigation link. |
| 30 | if ( empty( $block_data['blockName'] ) || 'core/navigation-link' !== $block_data['blockName'] ) { |
| 31 | return $content; |
| 32 | } |
| 33 | // don't have kind. |
| 34 | if ( empty( $block_data['attrs']['kind'] ) || 'sc-collection' !== $block_data['attrs']['kind'] ) { |
| 35 | return $content; |
| 36 | } |
| 37 | // don't have an id. |
| 38 | if ( empty( $block_data['attrs']['id'] ) ) { |
| 39 | return $content; |
| 40 | } |
| 41 | |
| 42 | $collection = ProductCollection::find( $block_data['attrs']['id'] ); |
| 43 | |
| 44 | if ( ! $collection || empty( $collection ) || empty( $collection->slug ) ) { |
| 45 | return $content; |
| 46 | } |
| 47 | |
| 48 | $collection_slug = $collection->slug; |
| 49 | |
| 50 | $new_link = esc_url_raw( trailingslashit( get_home_url() ) . trailingslashit( \SureCart::settings()->permalinks()->getBase( 'collection_page' ) ) . $collection_slug ); |
| 51 | |
| 52 | return preg_replace( '/href="([^"]*)"/', 'href="' . $new_link . '"', $content ); |
| 53 | } |
| 54 | } |
| 55 |