MODX: How to get the first image from a blog post for the Open Graph Protocol HTML head tags

Share this on:

I wrote a snippet so I could grab the first image in a blog article to populate the Open Graph Protocol image meta tag in the header:

  <meta property="og:image" content="[ [++site_url] ][ [ getFirstImageInResource ] ]" >

The text editor I'm using is Redactor but it should work just as well with other wysywig text editors.

So the snippet getFirstImageInResource looks like this:

<?php
$content = $modx->resource->content;
if(preg_match("/src=\"(.*?)\"/",$content,&$matches)){
    $img  = substr($matches[1],1,strlen($matches[1]));  
}    
else {
    $img  = "assets/images/defaultImage.png";      
}
return $img;

So we get the content, then search for the first instance of src="...the path to the image..." and we get the contents between the quotations, which is the image path.

I remove the first character because in my case it is a forward slash: / otherwise I end up with two in the path.

If there isn't an image in the article we have a default value to use.

Easy! Now whoever is writing the article doesn't have to worry about filling in another template variable to satisfy the social media protocols because it is done automatically.

Share this on:
Mike Nuttall

Author: Mike Nuttall

Mike has been web designing, programming and building web applications in Leeds for many years. He founded Onsitenow in 2009 and has been helping clients turn business ideas into on-line reality ever since. Mike can be followed on Twitter and has a profile on Google+.