Software Developer

Pass Parameters To Image Script in WordPress and Return Image Data URI

This snippet is an example of how to pass parameters to a PHP image script, in WordPress, and return an image data URI. This example is for when AJAX is not an option, and you don’t want to use the image script file as the image src attribute, but rather prefer to use an image data URI.

This supposes that you have some PHP file that creates an image, for example, using imagepng() or imagejpeg().

In this example, the filename is image.php. This example assumes that your image.php file is inside a plugin folder. Edit the URL on line 1 according to where your image script resides. Also on line 1, edit the URL parameters as needed for your case.

Line 3 passes the parameters to the image script which creates the image file. Lines 5-8 check for errors. Line 10 encodes the image file into a data URI. Line 12 is the HTML for the image element. Use the $html variable to display the image.

$url = plugin_dir_url( __FILE__ ) . "image.php?param1=$some_value&param2=$another_value";

$request = wp_remote_post( $url );

if ( is_wp_error( $request ) ) { // check for errors
	error_log( print_r( $request, true ) );
	return false;

$image_data = base64_encode( wp_remote_retrieve_body( $request ) );

$html = '<img src="data:image/png;base64,' . esc_attr( $image_data ) . '" alt="my image description">';


Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: