Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created February 2, 2017 13:04
Show Gist options
  • Select an option

  • Save rmpel/30ad0ce72235ffecbd26ad02ca1b54e9 to your computer and use it in GitHub Desktop.

Select an option

Save rmpel/30ad0ce72235ffecbd26ad02ca1b54e9 to your computer and use it in GitHub Desktop.
Add wp-image-ID class to images in content without them, as long as they are a WP upload. (UNTESTED!)
<?php
function wp_add_image_id_to_img_tags( $content ) {
if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
return $content;
}
$selected_images = array();
/*array*/$uploads = wp_upload_dir();
/*fullpath*/$uploads = $uploads['basedir'];
/*relpath*/$uploads = trim(str_replace(ABSPATH, '/', $uploads), '/');
/*regexp*/$uploads = str_replace('/', '\\/', $uploads);
// $content = $content . '<!-- REGEXP: /'. $uploads .'/i -->';
foreach( $matches[0] as $image ) {
if ( false === strpos( $image, ' srcset=' ) && !preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) && preg_match( '/src=["\'][^"\']*'. $uploads .'\/([^"\']+)["\']/i', $image, $src ) ) {
$selected_images[ $image ] = $src[1];
}
}
$index = array();
if ( count( $selected_images ) > 1 ) {
global $wpdb;
$srcs = "'". implode("', '", array_map('esc_sql', $selected_images)) ."'";
$attachment_list = $wpdb->get_results("SELECT post_id as id, meta_value as src FROM {$wpdb->postmeta} WHERE meta_value IN ($srcs) AND meta_key LIKE '%_attached_file'");
foreach ($attachment_list as $item) {
$index[ $item->src ] = $item->id;
}
foreach ($selected_images as $image => $src) {
$selected_images[ $image ] = array_key_exists($src, $index) ? my_add_class($image, 'wp-image-added wp-image-'. $index[ $src ]) : false;
}
$selected_images = array_filter($selected_images);
$content = strtr($content, $selected_images);
}
return $content;
}
function my_add_class($htmlpart, $classes) {
if ( false !== strpos($htmlpart, 'class=') ) {
$htmlpart = preg_replace('/class=(.)/', 'class=$1'. $classes .' ', $htmlpart);
}
else {
$htmlpart = explode(' ', $htmlpart);
$tag = array_shift($htmlpart);
array_unshift($htmlpart, 'class="'. $classes .'"');
array_unshift($htmlpart, $tag);
$htmlpart = implode(' ', $htmlpart);
}
return $htmlpart;
}
add_filter('the_content', 'wp_add_image_id_to_img_tags', 9);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment