repeat-visitor.php
58 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Repeat Visitor Block |
| 4 | * |
| 5 | * @since 7.2.0 |
| 6 | * |
| 7 | * @package automattic/jetpack |
| 8 | */ |
| 9 | |
| 10 | namespace Automattic\Jetpack\Extensions\Repeat_Visitor; |
| 11 | |
| 12 | use Automattic\Jetpack\Blocks; |
| 13 | use Jetpack_Gutenberg; |
| 14 | |
| 15 | const FEATURE_NAME = 'repeat-visitor'; |
| 16 | const BLOCK_NAME = 'jetpack/' . FEATURE_NAME; |
| 17 | |
| 18 | /** |
| 19 | * Registers the block for use in Gutenberg |
| 20 | * This is done via an action so that we can disable |
| 21 | * registration if we need to. |
| 22 | */ |
| 23 | function register_block() { |
| 24 | Blocks::jetpack_register_block( |
| 25 | BLOCK_NAME, |
| 26 | array( 'render_callback' => __NAMESPACE__ . '\render_block' ) |
| 27 | ); |
| 28 | } |
| 29 | add_action( 'init', __NAMESPACE__ . '\register_block' ); |
| 30 | |
| 31 | /** |
| 32 | * Repeat Visitor block dependency declaration. |
| 33 | * |
| 34 | * @param array $attributes Array containing the block attributes. |
| 35 | * @param string $content String containing the block content. |
| 36 | * |
| 37 | * @return string |
| 38 | */ |
| 39 | function render_block( $attributes, $content ) { |
| 40 | Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME ); |
| 41 | |
| 42 | $classes = Blocks::classes( FEATURE_NAME, $attributes ); |
| 43 | |
| 44 | $count = isset( $_COOKIE['jp-visit-counter'] ) ? (int) $_COOKIE['jp-visit-counter'] : 0; |
| 45 | $criteria = isset( $attributes['criteria'] ) ? $attributes['criteria'] : 'after-visits'; |
| 46 | $threshold = isset( $attributes['threshold'] ) ? (int) $attributes['threshold'] : 3; |
| 47 | |
| 48 | if ( |
| 49 | ( 'after-visits' === $criteria && $count >= $threshold ) || |
| 50 | ( 'before-visits' === $criteria && $count < $threshold ) |
| 51 | ) { |
| 52 | return $content; |
| 53 | } |
| 54 | |
| 55 | // return an empty div so that view script increments the visit counter in the cookie. |
| 56 | return '<div class="' . esc_attr( $classes ) . '"></div>'; |
| 57 | } |
| 58 |