Data URI in custom fields

Hook on ‘save_post’, and after normal saving metabox routine create the data uri using php functions base64_encode and file_get_contents.

With a bit of logic skip saving if not necessary (data uri already_saved).

In next example I assume the post thumbnail url is setted in a metabox, and the name of the field is ‘post_thumbnail’.

See comments in code for some info.

add_action( 'save_post', 'post_thumb_to_data_uri' ); 

function post_thumb_to_data_uri( $post_id ) { 
    // No auto saves 
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; 
    // make sure the current user can edit the post 
    $cap = get_post_type($post_id) == 'page' ? 'edit_page' : 'edit_post';
    if ( ! current_user_can( $cap, $post_id ) ) return;

    // assure the data are sended by the form and i a correct url
    if (
      ! isset($_POST['post_thumbnail']) ||
      ! filter_var($_POST['post_thumbnail'], 'FILTER_VALIDATE_URL')
    ) return;

   // check the nonce if you have
   if ( ! isset($_POST['nonce']) || ! wp_verify_nonce('nonce', 'nonce_value') ) return;

    // skip if data uri already saved for the url
    $now_url = get_post_meta($post_id, 'post_thumbnail', true);
    $now_data = get_post_meta($post_id, '_post_thumbnail_datauri_src', true);
    if ($now_url && $now_data && $now_url == esc_url($_POST['post_thumbnail']) ) return;

    // get the path from the url   
    $path = untrailingslashit(ABSPATH) . wp_make_link_relative($_POST['post_thumbnail']);

    // check file existence and type
    if ( ! file_exists($path) ) return;
    $mime = wp_check_filetype( $path );
    if (
      ! is_array($mime) || ! isset($mime['type']) || empty($mime['type']) ||
      ! substr_count($mime['type'], 'image') // assure is an image
    ) return;

    $datauri = base64_encode( @file_get_contents($path) );
    if ( empty($datauri) ) return;
    $src="https://wordpress.stackexchange.com/questions/111406/data:" . $mime['type'] . ';base64,' . $datauri;

    update_post_meta($post_id, '_post_thumbnail_datauri_src', $src);
    update_post_meta($post_id, 'post_thumbnail', esc_url($_POST['post_thumbnail']) );

}

An helper function will help to print it

function the_thumbnail_uri( $post = null, $echo = true ) {
   if ( empty($post) ) global $post;
   if ( is_int($post) ) $post = get_post($post);
   if ( ! is_object($post) ) return;
   $thumb = get_post_meta($post->ID, '_post_thumbnail_datauri_src', true);
   $alt = apply_filters('the_title', $post->post_title );
   if ( $thumb) 
     $img = '<img src="' . $thumb . '" alt="' . esc_attr($alt) . '"/>';
   if ( ! $echo ) return $img;
   echo $img;
}

In your template files:

while( have_posts() ) : the_post();

 the_thumbnail_uri();

endwhile;

Outside of the loop:

the_thumbnail_uri( $post ); // $post can be a post object or a post id 

tech