Support » Plugin: Jetpack by WordPress.com » Top Posts & Pages widget (Jetpack) questions

  • Resolved beardedgit

    (@beardedgit)


    I’m using the Top Posts & Pages widget (Jetpack) to display a 10-image grid in my sidebar. I’m using the widget in conjunction with the Code Snippets plugin and was wondering…

    1: if there’s a code snippet for making the widget ignore posts which don’t have images. The widget output looks quite boring when it shows multiple instances of my Gravatar 🙁

    2: if there’s a way to make the widget display random posts in the same style (10-image grid in sidebar).

    Any suggestions?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Jeremy Herve

    (@jeherve)

    Jetpack Mechanic 🚀

    1: if there’s a code snippet for making the widget ignore posts which don’t have images.

    You could use the jetpack_widget_get_top_posts filter to remove all posts without an image, like so:

    
    /**
     * Remove posts without an image from the Top Posts widget.
     *
     * @param array $posts Array of the most popular posts.
     * @param array $post_ids Array of Post IDs.
     * @param string $count Number of Top Posts we want to display.
     */
    function jeherve_skip_posts_without_image( $posts, $post_ids, $count ) {
    	foreach ( $posts as $k => $post ) {
    		// First, we'll look for an image for our post ID.
    		$image = Jetpack_PostImages::get_image( $post['post_id'], array( 'fallback_to_avatars' => false ) );
    
    		// Remove the post if no image exists for that post.
    		if ( ! is_array( $image ) ) {
    			unset( $posts[ $k ] );
    		}
    	}
    	return $posts;
    }
    add_filter( 'jetpack_widget_get_top_posts', 'jeherve_skip_posts_without_image' );

    if there’s a way to make the widget display random posts in the same style

    You could use that same filter again, and return a random list of posts instead of the popular posts.

    I hope this helps.

    Thank you – your code snippet works fine to remove posts without images.

    You could use that same filter again, and return a random list of posts instead of the popular posts.

    Sorry but can you tell me how, please? My grey-matter isn’t firing on all neurons like it used to.

    Plugin Author Jeremy Herve

    (@jeherve)

    Jetpack Mechanic 🚀

    Something like this should help:
    https://github.com/jeherve/jetpack-addons/blob/random-top-posts/jeherve-random-top-posts.php

    I added comments so you can understand how the list of Top Posts was replaced by a list of random posts that all include an image.

    That’s brilliant, Jeremy, thank you!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Top Posts & Pages widget (Jetpack) questions’ is closed to new replies.