-
Notifications
You must be signed in to change notification settings - Fork 9
Best Practices
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.
If you're working on a development environment, you might run into some issues while using this plugin.
So instead of using cloudinary_url()
directly, you might want to use something like this in your theme:
/**
* 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="">';
}
The example above gives priority to this plugin for the sake of simplicity. It 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.
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.