Skip to content

Instantly share code, notes, and snippets.

@nateplusplus
Last active December 15, 2018 00:51
Show Gist options
  • Save nateplusplus/82e2776bef155744feae9d7143aec193 to your computer and use it in GitHub Desktop.
Save nateplusplus/82e2776bef155744feae9d7143aec193 to your computer and use it in GitHub Desktop.
A migration to remove ALL links from images on all wordpress posts
/**
* A migration to remove ALL links from images on all wordpress posts
* Based on https://gist.github.com/cfxd/219f083465bb5b93fac8#file-remove_wp_selfies-php
**/
function remove_linked_images() {
$all_ids = new WP_Query(array(
'post_type' => array('post'), // feel free to add custom post types here if necessary
'posts_per_page' => -1,
'post_status' => 'publish',
'fields' => 'ids'
));
foreach($all_ids->posts as $id) {
$current_post = get_post($id);
$current_content = $current_post->post_content;
preg_match_all('/(<a.*?>)(<img.*?>)(<\/a>)/', $current_content, $matches);
$linked_images = $matches[0];
if (count($linked_images) > 0) {
$content_replaced = $current_content;
$wp_images = $matches[2];
foreach ( $linked_images as $key => $replace_str) {
$content_replaced = str_replace($replace_str, $wp_images[$key], $content_replaced);
}
wp_update_post(array(
'ID' => $id,
'post_content' => $content_replaced
));
}
}
}
add_action('admin_init', 'remove_linked_images');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment