How to use Photon to serve custom cropped Post thumbnails

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 50% off your first year.

Explore plans

The Photon module resizes your site’s images on the fly, without cropping them. However, in some cases you might want Photon to apply a custom cropping when resizing certain images.

In the following example, we will use photon to serve Post thumbnails with custom cropping, and use a different cropping on single pages:

if( function_exists( 'jetpack_photon_url' ) ) {
    add_filter( 'jetpack_photon_url', 'jetpack_photon_url', 10, 3 );
}
function jeherve_display_custom( $content, $post ) {

	global $post;

	// If you didn't define a post thumnail, let's forget about all this
	if ( !has_post_thumbnail( $post->ID ) )
		return $content;

	// What's the cropping and the size of image we should use on Single pages?
	// See http://developer.wordpress.com/docs/photon/api/#crop for parameters
	if ( is_single() ) {
		$args = array(
		    'crop'   => '50,50,200px,200px',
		);
	}
	// resizing on other pages
	else {
		$args = array(
		    'resize'   => '200,400',
		);
	}

	// Let's create a Photon Image URL from the Post Thumbnail
	$feat_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
	$photon_image_url = jetpack_photon_url( $feat_image_url[0], $args );

	// Let's build the image tag
	$our_image = sprintf( '<div class="post-media"><a class="featured-image" href="%1$s" title="%2$s"><img src="%3$s" class="wp-post-image" alt="Featured Image"></a></div>',
		esc_url( get_permalink() ),
		esc_attr( sprintf( __( 'Open %s', 'dot' ), get_the_title() ) ),
		esc_attr( $photon_image_url )
	);

	// Let's return the image, right before the post content
	return $our_image . $content;

}
add_filter( 'the_content', 'jeherve_display_custom' );

Reference

This entry was posted in Code snippets, Tips & Tricks and tagged , . Bookmark the permalink.

Jeremy Herve profile
Jeremy Herve

Jetpack Mechanic 🚀 at Automattic. WordPress, board games, TV Series, music.

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 50% off your first year.

Explore plans

Have a question?

Comments are closed for this article, but we're still here to help! Visit the support forum and we'll be happy to answer any questions.

View support forum
  • Enter your email address to follow this blog and receive news and updates from Jetpack!

    Join 112.8K other subscribers
  • Browse by Topic