Skip to content

Instantly share code, notes, and snippets.

@vicegold
Created February 27, 2018 09:14
Show Gist options
  • Save vicegold/450a4010d6c1e47a8c310672489a22b2 to your computer and use it in GitHub Desktop.
Save vicegold/450a4010d6c1e47a8c310672489a22b2 to your computer and use it in GitHub Desktop.
Remove first image in Wordpress post
<?php get_header();
/**
* Template Name: removeFirstImage
*
*/
?>
<div>
<?php
//this will return the attachment id
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
//set the arguments for our loop
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
);
//execute
$query = new WP_Query( $args );
$posts = $query->posts;
foreach ( $posts as $post ){
//echo "Post ID: " . $post->ID . "<br>";
$postid = $post->ID;
//echo $post->post_title . "<br>";
// get the full content of the post
$content = $post->post_content;
// find the first <img> tag and save to variable $imageUrl
preg_match('/\< *[img][^\>]*[.]*\>/i', $content, $imageUrl);
// [0] is just the image URL.
echo "The image url: <pre>" . $imageUrl[0] . "</pre><br>";
$newcontent = str_replace("$imageUrl[0]","",$content,$count);
// echo $newcontent;
// Update post the post
echo "Found url match in post: " . $postid . "<br>";
$my_post = array(
'ID' => $postid,
'post_content' => $newcontent,
);
// Update the post into the database
echo "Removed url, now updating the post! <br>";
wp_update_post( $my_post );
//echo "Imageurl: " . $imageUrl . "<br>";
// Uncomment if you want to add the image as featured image
// if ($imageUrl){
// $imageId = pippin_get_image_id($imageUrl);
// echo "Setting post thumbnail for attachment id: " . $imageId . "<br>";
// set_post_thumbnail($postid, $imageId);
// }
} //end foreach
?>
</div>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment