index.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Kubio\Blocks; |
| 4 | use Kubio\Core\Blocks\BlockBase; |
| 5 | use Kubio\Core\Registry; |
| 6 | use IlluminateAgnostic\Arr\Support\Arr; |
| 7 | use Kubio\Core\Utils; |
| 8 | |
| 9 | class PostExcerptBlock extends BlockBase { |
| 10 | const TEXT = 'text'; |
| 11 | |
| 12 | /** |
| 13 | * List of Kubio blocks which should be allowed in excerpts. |
| 14 | */ |
| 15 | const ALLOWED_EXCERPT_BLOCKS = array( 'kubio/text', 'kubio/heading' ); |
| 16 | |
| 17 | /** |
| 18 | * Retrieves the maximum number of words declared by the user. |
| 19 | * |
| 20 | * @return numeric |
| 21 | */ |
| 22 | public function getExcerptWordCount() { |
| 23 | return $this->getAttribute( 'wordCount', 16 ); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * This method will be passed to the `excerpt_allowed_blocks` filter and will add our ALLOWED_EXCERPT_BLOCKS |
| 28 | * |
| 29 | * @param $allowed_blocks array |
| 30 | * |
| 31 | * @return array |
| 32 | */ |
| 33 | public function excerpt_allowed_blocks( $allowed_blocks ) { |
| 34 | array_push( $allowed_blocks, ...self::ALLOWED_EXCERPT_BLOCKS ); |
| 35 | return $allowed_blocks; |
| 36 | } |
| 37 | |
| 38 | public function mapPropsToElements() { |
| 39 | add_filter( 'excerpt_allowed_blocks', array( $this, 'excerpt_allowed_blocks' ) ); |
| 40 | |
| 41 | $post_id = Arr::get( $this->block_context, 'postId', 0 ); |
| 42 | $post_type = Arr::get( $this->block_context, 'postType', 0 ); |
| 43 | |
| 44 | //workaround for http://mantis.extendstudio.net/view.php?id=39609 |
| 45 | if ( $post_type === 'page' && is_single( $post_id ) ) { |
| 46 | $content = ''; |
| 47 | |
| 48 | if ( is_user_logged_in() ) { |
| 49 | $content = Utils::getFrontendPlaceHolder( |
| 50 | sprintf( |
| 51 | '%s<br/><div class="kubio-frontent-placeholder--small">%s</div>', |
| 52 | __( 'Pages do not support excerpt by default.', 'kubio' ), |
| 53 | __( 'Edit this page and remove the current block or use it in a posts list.', 'kubio' ) |
| 54 | ) |
| 55 | ); |
| 56 | } |
| 57 | } else { |
| 58 | $content = ( get_the_excerpt( $post_id ) ); |
| 59 | |
| 60 | $show_hellip = false; |
| 61 | $word_count = $this->getAttribute( 'wordCount', 16 ); |
| 62 | $content = explode( ' ', $content ); |
| 63 | |
| 64 | if ( count( $content ) > $word_count ) { |
| 65 | $show_hellip = true; |
| 66 | } |
| 67 | $content = array_slice( $content, 0, $word_count - 1 ); |
| 68 | $content = implode( ' ', $content ); |
| 69 | if ( $show_hellip ) { |
| 70 | $content .= '[…]'; |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | return array( |
| 75 | self::TEXT => array( |
| 76 | 'innerHTML' => wp_kses_post( $content ), |
| 77 | 'tag' => 'p', |
| 78 | ), |
| 79 | ); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | |
| 84 | Registry::registerBlock( |
| 85 | __DIR__, |
| 86 | PostExcerptBlock::class, |
| 87 | array( |
| 88 | 'metadata' => '../text/block.json', |
| 89 | 'metadata_mixins' => array( './block.json' ), |
| 90 | ) |
| 91 | ); |
| 92 |