Skip to content

Instantly share code, notes, and snippets.

@yehudah
Created August 9, 2017 07:45
Show Gist options
  • Select an option

  • Save yehudah/51ea4d6fcd9fc4b3477d930a9d250ebd to your computer and use it in GitHub Desktop.

Select an option

Save yehudah/51ea4d6fcd9fc4b3477d930a9d250ebd to your computer and use it in GitHub Desktop.
Replace mail content images to embedded in WordPress
<?php
add_action( 'phpmailer_init', 'replace_to_embedded' );
function replace_to_embedded( $phpmailer ) {
$content = replace_img_src( $phpmailer->Body );
foreach ( $content['images'] as $image_url ) {
$path = parse_url( $image_url, PHP_URL_PATH );
$image_path = ABSPATH . $path;
$phpmailer->AddEmbeddedImage( $image_path, basename( $image_url ) );
}
$phpmailer->Body = $content['html'];
}
function replace_img_src( $html ) {
$doc = new DOMDocument();
$doc->loadHTML( $html );
$tags = $doc->getElementsByTagName( 'img' );
$images = array();
foreach ( $tags as $tag ) {
$old_src = $tag->getAttribute('src');
$image_id = basename( $old_src );
$new_src = 'cid:' . $image_id;
$tag->setAttribute( 'src', $new_src );
$images[] = $old_src;
}
return array( 'html' => $doc->saveHTML(), 'images' => $images );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment