related-posts.php
75 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Related Posts Block. |
| 4 | * |
| 5 | * @package automattic/jetpack |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack\Extensions\RelatedPosts; |
| 9 | |
| 10 | use Automattic\Jetpack\Blocks; |
| 11 | use Automattic\Jetpack\Modules; |
| 12 | use Automattic\Jetpack\Status; |
| 13 | use Automattic\Jetpack\Status\Host; |
| 14 | use WP_Block; |
| 15 | |
| 16 | /** |
| 17 | * Registers the block for use in Gutenberg |
| 18 | * This is done via an action so that we can disable |
| 19 | * registration if we need to. |
| 20 | */ |
| 21 | function register_block() { |
| 22 | /* |
| 23 | * The block is available even when the module is not active, |
| 24 | * so we can display a nudge to activate the module instead of the block. |
| 25 | * However, since non-admins cannot activate modules, we do not display the empty block for them. |
| 26 | */ |
| 27 | if ( ! ( new Modules() )->is_active( 'related-posts' ) && ! current_user_can( 'jetpack_activate_modules' ) ) { |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | if ( |
| 32 | ( new Host() )->is_wpcom_simple() |
| 33 | || ( \Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) |
| 34 | ) { |
| 35 | Blocks::jetpack_register_block( |
| 36 | __DIR__, |
| 37 | array( |
| 38 | 'render_callback' => __NAMESPACE__ . '\render_block', |
| 39 | ) |
| 40 | ); |
| 41 | } |
| 42 | } |
| 43 | add_action( 'init', __NAMESPACE__ . '\register_block', 9 ); |
| 44 | |
| 45 | /** |
| 46 | * Related Posts block render callback. |
| 47 | * |
| 48 | * @param array $attributes Array containing the Button block attributes. |
| 49 | * @param string $content The block content. |
| 50 | * @param WP_Block $block The block object. |
| 51 | * |
| 52 | * @return string |
| 53 | */ |
| 54 | function render_block( $attributes, $content, $block ) { |
| 55 | // If the Related Posts module is not active, don't render the block. |
| 56 | if ( |
| 57 | ! ( new Host() )->is_wpcom_simple() |
| 58 | && ! ( new Modules() )->is_active( 'related-posts' ) |
| 59 | ) { |
| 60 | return ''; |
| 61 | } |
| 62 | |
| 63 | // If the Related Posts option is turned off, don't render the block. |
| 64 | $options = \Jetpack_Options::get_option( 'relatedposts', array() ); |
| 65 | if ( empty( $options['enabled'] ) || ! $options['enabled'] ) { |
| 66 | return ''; |
| 67 | } |
| 68 | |
| 69 | if ( ! class_exists( 'Jetpack_RelatedPosts' ) ) { |
| 70 | require_once JETPACK__PLUGIN_DIR . 'modules/related-posts/jetpack-related-posts.php'; |
| 71 | } |
| 72 | |
| 73 | return \Jetpack_RelatedPosts::init()->render_block( $attributes, $content, $block ); |
| 74 | } |
| 75 |