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