挂接“save\\u post”,在正常保存metabox例程后,使用php函数创建数据uribase64_encode 和file_get_contents.
如果不需要(数据uri已保存),则略带逻辑跳过保存。
在下一个示例中,我假设post缩略图url设置在metabox中,字段名称为“post\\u缩略图”。
有关某些信息,请参见代码中的注释。
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 = \'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\']) );
}
 一个助手函数将帮助打印它
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;
}
 在模板文件中:
while( have_posts() ) : the_post();
 the_thumbnail_uri();
endwhile;
 环路外:
the_thumbnail_uri( $post ); // $post can be a post object or a post id