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