PluginProbe
WP Popular Posts / 7.4.2
WP Popular Posts v7.4.2
7.4.2 7.4.1 4.0.8 4.0.9 4.1.0 4.1.1 4.1.2 4.2.0 4.2.1 4.2.2 5.0.0 5.0.1 5.0.2 5.1.0 5.2.0 5.2.1 5.2.2 5.2.3 5.2.4 5.3.0 5.3.1 5.3.2 5.3.3 5.3.4 5.3.5 All 93 releases
wordpress-popular-posts / src / Rest / WidgetEndpoint.php
WidgetEndpoint.php
111 lines 3.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace WordPressPopularPosts\Rest;
3
4 use WordPressPopularPosts\{ Output, Translate };
5 use WordPressPopularPosts\Traits\QueriesPosts;
6
7 class WidgetEndpoint extends Endpoint {
8
9 use QueriesPosts;
10
11 /**
12 * Output object.
13 *
14 * @var \WordPressPopularPosts\Output $output
15 * @access private
16 */
17 protected $output;
18
19 /**
20 * Initializes class.
21 *
22 * @param array
23 * @param \WordPressPopularPosts\Translate
24 * @param \WordPressPopularPosts\Output
25 */
26 public function __construct(array $config, Translate $translate, Output $output)
27 {
28 $this->config = $config;
29 $this->translate = $translate;
30 $this->output = $output;
31 }
32
33 /**
34 * Registers the endpoint(s).
35 *
36 * @since 5.3.0
37 */
38 public function register()
39 {
40 $version = '2';
41 $namespace = 'wordpress-popular-posts/v' . $version;
42
43 register_rest_route($namespace, '/widget/', [
44 [
45 'methods' => 'POST',
46 'callback' => [$this, 'get_widget_block'],
47 'permission_callback' => '__return_true',
48 'args' => $this->get_widget_params(),
49 ]
50 ]);
51 }
52
53 /**
54 * Retrieves a popular posts widget for display.
55 *
56 * @since 5.4.0
57 *
58 * @param \WP_REST_Request $request Full details about the request.
59 * @return \WP_Error|\WP_REST_Response Response object on success, or WP_Error object on failure.
60 */
61 public function get_widget_block($request)
62 {
63 $instance = $request->get_params();
64
65 $is_single = $request->get_param('is_single');
66 $lang = $request->get_param('lang');
67
68 // Multilang support
69 $this->set_lang($lang);
70
71 $popular_posts = $this->maybe_query($instance);
72
73 if ( is_numeric($is_single) && $is_single > 0 ) {
74 add_filter('wpp_is_single', function($id) use ($is_single) {
75 return $is_single;
76 });
77 }
78
79 $this->output->set_data($popular_posts->get_posts());
80 $this->output->set_public_options($instance);
81 $this->output->build_output();
82
83 return [
84 'widget' => ( $this->config['tools']['cache']['active'] ? '<!-- cached -->' : '' ) . $this->output->get_output()
85 ];
86 }
87
88 /**
89 * Retrieves the query params for getting a widget instance.
90 *
91 * @since 4.1.0
92 *
93 * @return array Query parameters for getting a widget instance.
94 */
95 public function get_widget_params()
96 {
97 return [
98 'is_single' => [
99 'type' => 'integer',
100 'default' => null,
101 'sanitize_callback' => 'absint'
102 ],
103 'lang' => [
104 'type' => 'string',
105 'default' => null,
106 'sanitize_callback' => 'sanitize_text_field'
107 ],
108 ];
109 }
110 }
111