Completed
Push — branch-4.0 ( fc0d6f...bf547c )
by
unknown
08:22
created

Jetpack_Top_Posts_Widget::get_by_likes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * Currently, this widget depends on the Stats Module. To not load this file
5
 * when the Stats Module is not active would potentially bypass Jetpack's
6
 * fatal error detection on module activation, so we always load this file.
7
 * Instead, we don't register the widget if the Stats Module isn't active.
8
 */
9
10
/**
11
 * Register the widget for use in Appearance -> Widgets
12
 */
13
add_action( 'widgets_init', 'jetpack_top_posts_widget_init' );
14
15
function jetpack_top_posts_widget_init() {
16
	// Currently, this widget depends on the Stats Module
17
	if (
18
		( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM )
19
	&&
20
		! function_exists( 'stats_get_csv' )
21
	) {
22
		return;
23
	}
24
25
	register_widget( 'Jetpack_Top_Posts_Widget' );
26
}
27
28
class Jetpack_Top_Posts_Widget extends WP_Widget {
29
	public $alt_option_name = 'widget_stats_topposts';
30
	public $default_title = '';
31
32
	function __construct() {
33
		parent::__construct(
34
			'top-posts',
35
			/** This filter is documented in modules/widgets/facebook-likebox.php */
36
			apply_filters( 'jetpack_widget_name', __( 'Top Posts &amp; Pages', 'jetpack' ) ),
37
			array(
38
				'description' => __( 'Shows your most viewed posts and pages.', 'jetpack' ),
39
				'customize_selective_refresh' => true,
40
			)
41
		);
42
43
		$this->default_title =  __( 'Top Posts &amp; Pages', 'jetpack' );
44
45 View Code Duplication
		if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
46
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ) );
47
		}
48
49
		/**
50
		 * Add explanation about how the statistics are calculated.
51
		 *
52
		 * @module widgets
53
		 *
54
		 * @since 3.9.3
55
		 */
56
		add_action( 'jetpack_widget_top_posts_after_fields', array( $this, 'stats_explanation' ) );
57
	}
58
59
	function enqueue_style() {
60
		wp_register_style( 'jetpack-top-posts-widget', plugins_url( 'top-posts/style.css', __FILE__ ), array(), '20141013' );
61
		wp_enqueue_style( 'jetpack-top-posts-widget' );
62
	}
63
64
	function form( $instance ) {
65
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
66
67
		$title = stripslashes( $instance['title'] );
68
69
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : 10;
70
		if ( $count < 1 || 10 < $count ) {
71
			$count = 10;
72
		}
73
74
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
75
		$types = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
76
77
		// 'likes' are not available in Jetpack
78
		$ordering = isset( $instance['ordering'] ) && 'likes' === $instance['ordering'] ? 'likes' : 'views';
79
80 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
81
			$display = $instance['display'];
82
		} else {
83
			$display = 'text';
84
		}
85
86
		?>
87
88
		<p>
89
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
90
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
91
		</p>
92
93
		<p>
94
			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php esc_html_e( 'Maximum number of posts to show (no more than 10):', 'jetpack' ); ?></label>
95
			<input id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" type="number" value="<?php echo (int) $count; ?>" min="1" max="10" />
96
		</p>
97
98
		<?php if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) : ?>
99
		<p>
100
			<label><?php esc_html_e( 'Order Top Posts &amp; Pages By:', 'jetpack' ); ?></label>
101
			<ul>
102
				<li><label><input id="<?php echo $this->get_field_id( 'ordering' ); ?>-likes" name="<?php echo $this->get_field_name( 'ordering' ); ?>" type="radio" value="likes" <?php checked( 'likes', $ordering ); ?> /> <?php esc_html_e( 'Likes', 'jetpack' ); ?></label></li>
103
				<li><label><input id="<?php echo $this->get_field_id( 'ordering' ); ?>-views" name="<?php echo $this->get_field_name( 'ordering' ); ?>" type="radio" value="views" <?php checked( 'views', $ordering ); ?> /> <?php esc_html_e( 'Views', 'jetpack' ); ?></label></li>
104
			</ul>
105
		</p>
106
		<?php endif; ?>
107
108
		<p>
109
			<label for="<?php echo $this->get_field_id( 'types' ); ?>"><?php esc_html_e( 'Types of pages to display:', 'jetpack' ); ?></label>
110
			<ul>
111
				<?php foreach( $allowed_post_types as $type ) {
112
					// Get the Post Type name to display next to the checkbox
113
					$post_type_object = get_post_type_object( $type );
114
					$label = $post_type_object->labels->name;
115
116
					$checked = '';
117
					if ( in_array( $type, $types ) ) {
118
						$checked = 'checked="checked" ';
119
					} ?>
120
121
					<li><label>
122
						<input value="<?php echo esc_attr( $type ); ?>" name="<?php echo $this->get_field_name( 'types' ); ?>[]" id="<?php echo $this->get_field_id( 'types' ); ?>-<?php echo $type; ?>" type="checkbox" <?php echo $checked; ?>>
123
						<?php echo esc_html( $label ); ?>
124
					</label></li>
125
126
				<?php } // End foreach ?>
127
			</ul>
128
		</p>
129
130
		<p>
131
			<label><?php esc_html_e( 'Display as:', 'jetpack' ); ?></label>
132
			<ul>
133
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-text" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="text" <?php checked( 'text', $display ); ?> /> <?php esc_html_e( 'Text List', 'jetpack' ); ?></label></li>
134
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-list" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="list" <?php checked( 'list', $display ); ?> /> <?php esc_html_e( 'Image List', 'jetpack' ); ?></label></li>
135
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-grid" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="grid" <?php checked( 'grid', $display ); ?> /> <?php esc_html_e( 'Image Grid', 'jetpack' ); ?></label></li>
136
			</ul>
137
		</p><?php
138
139
		/**
140
		 * Fires after the fields are displayed in the Top Posts Widget settings in wp-admin.
141
		 *
142
		 * Allow adding extra content after the fields are displayed.
143
		 *
144
		 * @module widgets
145
		 *
146
		 * @since 3.9.3
147
		 *
148
		 * @param array $args {
149
		 *     @param array $instance The widget instance.
150
		 *     @param object $this The class object.
151
		 * }
152
		 */
153
		do_action( 'jetpack_widget_top_posts_after_fields', array( $instance, $this ) );
154
	}
155
156
	/**
157
	 * Explains how the statics are calculated.
158
	 */
159
	function stats_explanation() {
160
		?>
161
162
		<p><?php esc_html_e( 'Top Posts &amp; Pages by views are calculated from 24-48 hours of stats. They take a while to change.', 'jetpack' ); ?></p><?php
163
	}
164
165
	function update( $new_instance, $old_instance ) {
166
		$instance = array();
167
		$instance['title'] = wp_kses( $new_instance['title'], array() );
168
		if ( $instance['title'] === $this->default_title ) {
169
			$instance['title'] = false; // Store as false in case of language change
170
		}
171
172
		$instance['count'] = (int) $new_instance['count'];
173
		if ( $instance['count'] < 1 || 10 < $instance['count'] ) {
174
			$instance['count'] = 10;
175
		}
176
177
		// 'likes' are not available in Jetpack
178
		$instance['ordering'] = isset( $new_instance['ordering'] ) && 'likes' == $new_instance['ordering'] ? 'likes' : 'views';
179
180
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
181
		$instance['types'] = $new_instance['types'];
182
		foreach( $new_instance['types'] as $key => $type ) {
183
			if ( ! in_array( $type, $allowed_post_types ) ) {
184
				unset( $new_instance['types'][ $key ] );
185
			}
186
		}
187
188 View Code Duplication
		if ( isset( $new_instance['display'] ) && in_array( $new_instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
189
			$instance['display'] = $new_instance['display'];
190
		} else {
191
			$instance['display'] = 'text';
192
		}
193
194
		/**
195
		 * Filters Top Posts Widget settings before they're saved.
196
		 *
197
		 * @module widgets
198
		 *
199
		 * @since 3.9.3
200
		 *
201
		 * @param array $instance The santized widget instance. Only contains data processed by the current widget.
202
		 * @param array $new_instance The new widget instance before sanitization.
203
		 */
204
		$instance = apply_filters( 'jetpack_top_posts_saving', $instance, $new_instance );
205
206
		return $instance;
207
	}
208
209
	function widget( $args, $instance ) {
210
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
211
212
		$title = isset( $instance['title' ] ) ? $instance['title'] : false;
213
		if ( false === $title ) {
214
			$title = $this->default_title;
215
		}
216
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
217
		$title = apply_filters( 'widget_title', $title );
218
219
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : false;
220
		if ( $count < 1 || 10 < $count ) {
221
			$count = 10;
222
		}
223
		/**
224
		 * Control the number of displayed posts.
225
		 *
226
		 * @module widgets
227
		 *
228
		 * @since 3.3.0
229
		 *
230
		 * @param string $count Number of Posts displayed in the Top Posts widget. Default is 10.
231
		 */
232
		$count = apply_filters( 'jetpack_top_posts_widget_count', $count );
233
234
		$types = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
235
236
		// 'likes' are not available in Jetpack
237
		$ordering = isset( $instance['ordering'] ) && 'likes' == $instance['ordering'] ? 'likes' : 'views';
238
239 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
240
			$display = $instance['display'];
241
		} else {
242
			$display = 'text';
243
		}
244
245
		if ( 'text' != $display ) {
246
			$get_image_options = array(
247
				'fallback_to_avatars' => true,
248
				/** This filter is documented in modules/shortcodes/audio.php */
249
				'gravatar_default' => apply_filters( 'jetpack_static_url', set_url_scheme( 'http://en.wordpress.com/i/logo/white-gray-80.png' ) ),
250
			);
251
			if ( 'grid' == $display ) {
252
				$get_image_options['avatar_size'] = 200;
253
			} else {
254
				$get_image_options['avatar_size'] = 40;
255
			}
256
			/**
257
			 * Top Posts Widget Image options.
258
			 *
259
			 * @module widgets
260
			 *
261
			 * @since 1.8.0
262
			 *
263
			 * @param array $get_image_options {
264
			 * Array of Image options.
265
			 * @type bool true Should we default to Gravatars when no image is found? Default is true.
266
			 * @type string $gravatar_default Default Image URL if no Gravatar is found.
267
			 * @type int $avatar_size Default Image size.
268
			 * }
269
			 */
270
			$get_image_options = apply_filters( 'jetpack_top_posts_widget_image_options', $get_image_options );
271
		}
272
273
		if ( function_exists( 'wpl_get_blogs_most_liked_posts' ) && 'likes' == $ordering ) {
274
			$posts = $this->get_by_likes( $count );
275
		} else {
276
			$posts = $this->get_by_views( $count, $args );
277
		}
278
279
		// Filter the returned posts. Remove all posts that do not match the chosen Post Types.
280
		if ( isset( $types ) ) {
281
			foreach ( $posts as $k => $post ) {
282
				if ( ! in_array( $post['post_type'], $types ) ) {
283
					unset( $posts[$k] );
284
				}
285
			}
286
		}
287
288
		if ( ! $posts ) {
289
			$posts = $this->get_fallback_posts();
290
		}
291
292
		echo $args['before_widget'];
293
		if ( ! empty( $title ) )
294
			echo $args['before_title'] . $title . $args['after_title'];
295
296
		if ( ! $posts ) {
297
			if ( current_user_can( 'edit_theme_options' ) ) {
298
				echo '<p>' . sprintf(
299
					__( 'There are no posts to display. <a href="%s" target="_blank">Want more traffic?</a>', 'jetpack' ),
300
					'http://en.support.wordpress.com/getting-more-site-traffic/'
301
				) . '</p>';
302
			}
303
304
			echo $args['after_widget'];
305
			return;
306
		}
307
308
		switch ( $display ) {
309
		case 'list' :
310
		case 'grid' :
311
			wp_enqueue_style( 'widget-grid-and-list' );
312
			foreach ( $posts as &$post ) {
313
				$image = Jetpack_PostImages::get_image( $post['post_id'], array( 'fallback_to_avatars' => true ) );
314
				$post['image'] = $image['src'];
315
				if ( 'blavatar' != $image['from'] && 'gravatar' != $image['from'] ) {
316
					$size = (int) $get_image_options['avatar_size'];
0 ignored issues
show
Bug introduced by
The variable $get_image_options does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
317
					$post['image'] = jetpack_photon_url( $post['image'], array( 'resize' => "$size,$size" ) );
318
				}
319
			}
320
321
			unset( $post );
322
323
			if ( 'grid' == $display ) {
324
				echo "<div class='widgets-grid-layout no-grav'>\n";
325
				foreach ( $posts as $post ) :
326
				?>
327
					<div class="widget-grid-view-image">
328
						<?php
329
						/**
330
						 * Fires before each Top Post result, inside <li>.
331
						 *
332
						 * @module widgets
333
						 *
334
						 * @since 3.2.0
335
						 *
336
						 * @param string $post['post_id'] Post ID.
337
						 */
338
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
339
						?>
340
						<a href="<?php echo esc_url( $post['permalink'] ); ?>" title="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" class="bump-view" data-bump-view="tp">
341
							<?php $size = (int) $get_image_options['avatar_size']; ?>
342
							<img width="<?php echo absint( $size ); ?>" height="<?php echo absint( $size ); ?>" src="<?php echo esc_url( $post['image'] ); ?>" alt="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" data-pin-nopin="true" />
343
						</a>
344
						<?php
345
						/**
346
						 * Fires after each Top Post result, inside <li>.
347
						 *
348
						 * @module widgets
349
						 *
350
						 * @since 3.2.0
351
						 *
352
						 * @param string $post['post_id'] Post ID.
353
						 */
354
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
355
						?>
356
					</div>
357
				<?php
358
				endforeach;
359
				echo "</div>\n";
360
			} else {
361
				echo "<ul class='widgets-list-layout no-grav'>\n";
362
				foreach ( $posts as $post ) :
363
				?>
364
					<li>
365
						<?php
366
						/** This action is documented in modules/widgets/top-posts.php */
367
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
368
						?>
369
						<a href="<?php echo esc_url( $post['permalink'] ); ?>" title="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" class="bump-view" data-bump-view="tp">
370
							<?php $size = (int) $get_image_options['avatar_size']; ?>
371
							<img width="<?php echo absint( $size ); ?>" height="<?php echo absint( $size ); ?>" src="<?php echo esc_url( $post['image'] ); ?>" class='widgets-list-layout-blavatar' alt="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" data-pin-nopin="true" />
372
						</a>
373
						<div class="widgets-list-layout-links">
374
							<a href="<?php echo esc_url( $post['permalink'] ); ?>" class="bump-view" data-bump-view="tp">
375
								<?php echo esc_html( wp_kses( $post['title'], array() ) ); ?>
376
							</a>
377
						</div>
378
						<?php
379
						/** This action is documented in modules/widgets/top-posts.php */
380
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
381
						?>
382
					</li>
383
				<?php
384
				endforeach;
385
				echo "</ul>\n";
386
			}
387
			break;
388
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
389
			echo '<ul>';
390
			foreach ( $posts as $post ) :
391
			?>
392
				<li>
393
					<?php
394
					/** This action is documented in modules/widgets/top-posts.php */
395
					do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
396
					?>
397
					<a href="<?php echo esc_url( $post['permalink'] ); ?>" class="bump-view" data-bump-view="tp">
398
						<?php echo esc_html( wp_kses( $post['title'], array() ) ); ?>
399
					</a>
400
					<?php
401
					/** This action is documented in modules/widgets/top-posts.php */
402
					do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
403
					?>
404
				</li>
405
			<?php
406
			endforeach;
407
			echo '</ul>';
408
		}
409
410
		echo $args['after_widget'];
411
	}
412
413
	public static function defaults() {
414
		return array(
415
			'title'    => esc_html__( 'Top Posts &amp; Pages', 'jetpack' ),
416
			'count'    => absint( 10 ),
417
			'types'    => array( 'post', 'page' ),
418
			'ordering' => 'views',
419
			'display'  => 'text',
420
		);
421
	}
422
423
	/*
424
	 * Get most liked posts
425
	 *
426
	 * ONLY TO BE USED IN WPCOM
427
	 */
428
	function get_by_likes( $count ) {
429
		$post_likes = wpl_get_blogs_most_liked_posts();
430
		if ( !$post_likes ) {
431
			return array();
432
		}
433
434
		return $this->get_posts( array_keys( $post_likes ), $count );
435
	}
436
437
	function get_by_views( $count, $args ) {
438
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
439
			global $wpdb;
440
441
			$post_views = wp_cache_get( "get_top_posts_$count", 'stats' );
442
			if ( false === $post_views ) {
443
				$post_views = array_shift( stats_get_daily_history( false, get_current_blog_id(), 'postviews', 'post_id', false, 2, '', $count * 2 + 10, true ) );
0 ignored issues
show
Bug introduced by
stats_get_daily_history(... $count * 2 + 10, true) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
444
				unset( $post_views[0] );
445
				wp_cache_add( "get_top_posts_$count", $post_views, 'stats', 1200);
446
			}
447
448
			return $this->get_posts( array_keys( $post_views ), $count );
449
		}
450
451
		/**
452
		 * Filter the number of days used to calculate Top Posts for the Top Posts widget.
453
		 *
454
		 * @module widgets
455
		 *
456
		 * @since 3.9.3
457
		 *
458
		 * @param int 2 Number of days. Default is 2.
459
		 * @param array $args The widget arguments.
460
		 */
461
		$days = (int) apply_filters( 'jetpack_top_posts_days', 2, $args );
462
463
		if ( $days < 1 ) {
464
			$days = 2;
465
		}
466
467
		if ( $days > 10 ) {
468
			$days = 10;
469
		}
470
471
		$post_view_posts = stats_get_csv( 'postviews', array( 'days' => absint( $days ), 'limit' => 11 ) );
472
		if ( ! $post_view_posts ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $post_view_posts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
473
			return array();
474
		}
475
476
		$post_view_ids = array_filter( wp_list_pluck( $post_view_posts, 'post_id' ) );
477
		if ( ! $post_view_ids ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $post_view_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
478
			return array();
479
		}
480
481
		return $this->get_posts( $post_view_ids, $count );
482
	}
483
484
	function get_fallback_posts() {
485
		if ( current_user_can( 'edit_theme_options' ) ) {
486
			return array();
487
		}
488
489
		$post_query = new WP_Query;
490
491
		$posts = $post_query->query( array(
492
			'posts_per_page' => 1,
493
			'post_status' => 'publish',
494
			'post_type' => array( 'post', 'page' ),
495
			'no_found_rows' => true,
496
		) );
497
498
		if ( ! $posts ) {
499
			return array();
500
		}
501
502
		$post = array_pop( $posts );
503
504
		return $this->get_posts( $post->ID, 1 );
505
	}
506
507
	function get_posts( $post_ids, $count ) {
508
		$counter = 0;
509
510
		$posts = array();
511
		foreach ( (array) $post_ids as $post_id ) {
512
			$post = get_post( $post_id );
513
514
			if ( ! $post )
515
				continue;
516
517
			// hide private and password protected posts
518
			if ( 'publish' != $post->post_status || ! empty( $post->post_password ) || empty( $post->ID ) )
519
				continue;
520
521
			// Both get HTML stripped etc on display
522
			if ( empty( $post->post_title ) ) {
523
				$title_source = $post->post_content;
524
				$title = wp_html_excerpt( $title_source, 50 );
525
				$title .= '&hellip;';
526
			} else {
527
				$title = $post->post_title;
528
			}
529
530
			$permalink = get_permalink( $post->ID );
531
532
			$post_type = $post->post_type;
533
534
			$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
535
			$counter++;
536
537
			if ( $counter == $count ) {
538
				break; // only need to load and show x number of likes
539
			}
540
		}
541
542
		/**
543
		 * Filter the Top Posts and Pages.
544
		 *
545
		 * @module widgets
546
		 *
547
		 * @since 3.0.0
548
		 *
549
		 * @param array $posts Array of the most popular posts.
550
		 * @param array $post_ids Array of Post IDs.
551
		 * @param string $count Number of Top Posts we want to display.
552
		 */
553
		return apply_filters( 'jetpack_widget_get_top_posts', $posts, $post_ids, $count );
554
	}
555
}
556
557
/**
558
 * Create a shortcode to display the widget anywhere.
559
 *
560
 * @since 3.9.2
561
 */
562
function jetpack_do_top_posts_widget( $instance ) {
563
	// Post Types can't be entered as an array in the shortcode parameters.
564
	if ( isset( $instance['types'] ) && is_array( $instance['types'] ) ) {
565
		$instance['types'] = implode( ',', $instance['types'] );
566
	}
567
568
	$instance = shortcode_atts(
569
		Jetpack_Top_Posts_Widget::defaults(),
570
		$instance,
571
		'jetpack_top_posts_widget'
572
	);
573
574
	// Add a class to allow styling
575
	$args = array(
576
		'before_widget' => sprintf( '<div class="%s">', 'jetpack_top_posts_widget' ),
577
	);
578
579
	ob_start();
580
	the_widget( 'Jetpack_Top_Posts_Widget', $instance, $args );
581
	$output = ob_get_clean();
582
583
	return $output;
584
}
585
add_shortcode( 'jetpack_top_posts_widget', 'jetpack_do_top_posts_widget' );
586