Jump to content

Recommended Posts

Posted

I have a page which lists articles, and if there are images uploaded via the images field for that page, a thumbnail is displayed next to the article headline.

However for a number of pages, I will be placing an existing image from another page in the tree into the body field. In these cases, is there anyway to check the body field's content for an image so I can display that in the article list?

Logic would be:

If the image field has one or more images uploaded { get first and display as thumbnail }

elseif the body field has one or more images placed from another page { use the first body image as the thumbnail }

else { omit thumbnail }

Anything I can try that would work as shown (or is there an alternative to consider)?

Thanks in advance!

Posted

Checking if a body field has an image in it or not should be as simple as:

if (strpos($page->body, "<img") !== false) { 
	// contains at least one image
}

 

Posted
1 minute ago, creativejay said:

Yes that does the trick for detecting the image, thanks, but how can I go about referencing the first image from $page->body in the template php?

What you want is domdocument:

Google this: php domdocument get first image

  • Like 1
Posted

Here's what I ended up with:

$artthumb = '';
if(count($a->images) > 0) {
		$artimage = $a->images->first();
		$artthumb = $artimage->url;
		if($artimage->description) {
			$imgdescript = $artimage->description;
		} else {
			$imgdescript = $a->getUnformatted('headline|title');
		}
		echo "<div class='col span_1_of_12'>";
		echo "<img src='{$artthumb}' title='{$imgdescript}' class='article-img' />";
		echo "</div>"; 
	} elseif (strpos($a->body, "<img") !== false) { 
		$texthtml = $a->body;
	    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image);
	    $artthumb = $image['src'];
	    $imgdescript = $a->getUnformatted('headline|title');
	    echo "<div class='col span_1_of_12'>";
		echo "<img src='{$artthumb}' title='{$imgdescript}' class='article-img' />";
		echo "</div>"; 
	} 

$a being the individual page in the foreach($articles as $a) loop.

  • Like 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...