Remove first image from a wordpress post(the_content)

So tired… soul searching… I was looking for a solution to remove the first image from wordpress posts. I’ve found some, but they didn’t work. So, I decided to make my own code:

Just put it on your “functions.php” file.

?Download download.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function clear_first_image($content) {
	/*
		Warning:
		# I know light sabers are better...
			...but maybe I'm not good enough, so I use laser guns 
		# It is not an elegant solution, but it works
		# Maybe someday I'll change it to use more regular expressions than logic
		# It's not recommended use this solution when you are
		processing large amount of data, like when you are on a loop
		# To call it on your code, under a loop(like "while" or "for"), use:
			echo clear_first_image(get_the_content())
 
		# Good luck! May the force be with you!
		alvaron8@gmail.com
	*/
	// checks if there is a first image
	$postst = strpos($content, '<img');
	if($postst !== false):
		// #letz check if the image has a link and remove it
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
		$link_img = $matches [1] [0];
		if($link_img!=""):
			// we get the first link 'begin' tag
			$lnkini = strpos($content , '<a href', 0);
			// then we get the first link 'close' tag
			$lnkend = strpos($content, '<img', $lnkini);
			// letz get the hole first link tag now
			$replnk = substr($content, $lnkini, ($lnkend-$lnkini));
			// now we replace the first link tag in the content
			$tmpctd = preg_replace("'".$replnk."'",'',$content);
			// letz clear the link tag close
			$lnkcld = strpos($content , '</a>', 0);
			$content = substr($tmpctd, 0, $lnkcld).substr($tmpctd, $lnkcld, strlen($tmpctd));
		endif;
		// #removing the first image
			// we get the first image 'open' tag
			$posini = strpos($content , '<img', 0);
			// then we get the first image 'close' tag
			$posend = strpos($content, '>', $posini);
			// letz get the hole first image tag now
			$repimg = substr($content, $posini, ($posend-$posini)+1);
			// now we replace the first image tag in the content
			$postOutput = preg_replace("'".$repimg."'",'',$content);
	else:
		$postOutput=$content;
	endif;
	return $postOutput;
}

And call it on your code, like this:

echo clear_first_image(get_the_content());
Share on TwitterSave on DeliciousShare via email