Posts.php
8 months ago
Shortcode.php
8 months ago
ShortcodeLoader.php
8 months ago
ViewsCount.php
8 months ago
ViewsCount.php
91 lines
| 1 | <?php |
| 2 | namespace WordPressPopularPosts\Shortcode; |
| 3 | |
| 4 | use WordPressPopularPosts\Helper; |
| 5 | use WordPressPopularPosts\Shortcode\Shortcode; |
| 6 | |
| 7 | class ViewsCount extends Shortcode { |
| 8 | |
| 9 | /** |
| 10 | * Construct. |
| 11 | */ |
| 12 | public function __construct() |
| 13 | { |
| 14 | $this->tag = 'wpp_views_count'; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Handles the HTML output of the shortcode. |
| 19 | * |
| 20 | * @since 6.3.0 |
| 21 | * @param mixed $attributes Array of attributes passed to the shortcode, or an empty string if nothing is passed |
| 22 | * @return string Views count |
| 23 | */ |
| 24 | public function handle($attributes = []) : string |
| 25 | { |
| 26 | $views = ''; |
| 27 | |
| 28 | if ( function_exists('wpp_get_views') ) { |
| 29 | $attributes = shortcode_atts( |
| 30 | [ |
| 31 | 'post_id' => null, |
| 32 | 'range' => 'all', |
| 33 | 'time_unit' => 'hour', |
| 34 | 'time_quantity' => 24, |
| 35 | 'number_format' => 1, |
| 36 | 'include_views_text' => 1 |
| 37 | ], |
| 38 | $attributes, |
| 39 | $this->tag |
| 40 | ); |
| 41 | |
| 42 | if ( ! $attributes['post_id'] ) { |
| 43 | if ( is_singular() ) { |
| 44 | $attributes['post_id'] = \get_queried_object_id(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | if ( $attributes['post_id'] && is_numeric($attributes['post_id']) ) { |
| 49 | $valid_time_ranges = ['last24hours', 'last7days', 'last30days', 'all', 'custom']; |
| 50 | |
| 51 | if ( |
| 52 | 'all' === $attributes['range'] |
| 53 | || ! in_array($attributes['range'], $valid_time_ranges) |
| 54 | ) { |
| 55 | $views = wpp_get_views($attributes['post_id'], 'all', false); |
| 56 | } elseif ( 'custom' !== $attributes['range'] ) { |
| 57 | $views = wpp_get_views($attributes['post_id'], $attributes['range'], false); |
| 58 | } else { |
| 59 | $views = wpp_get_views( |
| 60 | $attributes['post_id'], |
| 61 | [ |
| 62 | 'range' => 'custom', |
| 63 | 'time_unit' => $attributes['time_unit'], |
| 64 | 'time_quantity' => $attributes['time_quantity'] |
| 65 | ], |
| 66 | false |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | $views = (int) $views; |
| 71 | $views_string = $views; |
| 72 | |
| 73 | if ( $views && $attributes['number_format'] ) { |
| 74 | $views_string = ( 'prettify' === $attributes['number_format'] ) ? Helper::prettify_number($views) : number_format_i18n($views); |
| 75 | } |
| 76 | |
| 77 | if ( $attributes['include_views_text'] ) { |
| 78 | return sprintf( |
| 79 | _n('%s view', '%s views', $views, 'wordpress-popular-posts'), |
| 80 | $views_string |
| 81 | ); |
| 82 | } |
| 83 | |
| 84 | return $views_string; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | return $views; |
| 89 | } |
| 90 | } |
| 91 |