Skip to content

Best Practices

Junaid Bhura edited this page May 30, 2021 · 6 revisions

Keep your image code abstract

If you decide to stop using Cloudinary or this plugin at some point because you want to use some other image service or plugin, or maybe your own code to best suit your website, you don't want to be stuck with a bunch of cloudinary_url()s in your theme.

So instead of using cloudinary_url() directly, you might want to use something like this in your theme:

function my_theme_image_url( $id = 0, $args = array() ) {
	// Check for Auto Cloudinary plugin.
	if ( function_exists( 'cloudinary_url' ) ) {
		return cloudinary_url( $id, $args );
	} else {
		// Auto Cloudinary plugin not active, fall back to the original image's URL.
		// Replace this with whatever suits your needs.
		return wp_get_attachment_url( $id );
	}
}

So if you want to switch between different image plugins or providers, you just need to make a change in this one function, instead of multiple places in your code.

Advanced Example

If you're working on a development environment, you might run into some issues while using this plugin. Here's an example which uses Fly Dynamic Image Resizer as a fallback locally.

The following example falls back to the Fly Dynamic Image Resizer plugin. You can come up with your own function which best suits your theme and long-term needs. You don't want to be stuck with $args which look like what this plugin offers.

/**
 * Get a dynamic image URL.
 * 
 * @param  int   $id
 * @param  array $args
 * @return string
 */
function my_theme_image_url( $id = 0, $args = array() ) {
	// Check for Auto Cloudinary plugin.
	if ( function_exists( 'cloudinary_url' ) ) {
		$image_url = cloudinary_url( $id, $args );
	} else {
		// Plugin does not exist, maybe it's a development environment?
		// Let's use Fly Dynamic Image Resizer instead!
		$image_src = fly_get_attachment_image_src( $id, array( $args['transform']['width'], $args['transform']['height'] ), true );
		$image_url = $image_src[0];
	}
	return $image_url;
}

/**
 * Build an HTML image tag.
 *
 * @param  int   $id
 * @param  array $args
 * @return string
 */
function my_theme_image( $id, $args ) {
	// Custom SRCSET.
	$srcset = '';

	// Check for Auto Cloudinary plugin.
	if ( function_exists( 'cloudinary_url' ) ) {
		$original_url = cloudinary_get_original_url( $id );
		$sizes = array(
			my_theme_image_url( $original_url, array(
				'transform' => array(
					'width' => 1000,
				),
			) ) . ' 1000 w',
			my_theme_image_url( $original_url, array(
				'transform' => array(
					'width' => 500,
				),
			) ) . ' 500 w',
		);
		$srcset = ' srcset="' . implode( ', ', $sizes ) . '" sizes="(min-width: 1000px) 50vw, 100vw"';
	}

	// Manipulate ALT and TITLE attributes.

	// Return the image.
	return '<img src="' . my_theme_image_url( $id, $args ) . '" width="' . $args['transform']['width'] . ' height="' . $args['transform']['height'] . '"' . $srcset . ' alt="">';
}
Clone this wiki locally