Skip to content

Instantly share code, notes, and snippets.

@vajrasar
Last active December 23, 2015 11:18
Show Gist options
  • Save vajrasar/6627113 to your computer and use it in GitHub Desktop.
Save vajrasar/6627113 to your computer and use it in GitHub Desktop.
This code gets the first image of the post (not the featured image) and places it above the Post Title and in second step it removes the first-image-of-content (the_content) from post content to remove same image showing twice (above title and in content). Code goes in functions.php
<?php
//to catch & print first image occuring in post content (the_content) via famous 'catch-that-image'
/* we could have also used genesis_get_image() to catch the first image instead of 'catch_that_image' script;
but genesis_get_image() was actually catching "first uploaded image" instead of "first image occuring in the_content".
Link to snippet using genesis_get_image -- https://gist.github.com/vajrasar/6559551
*/
add_action('genesis_entry_header','image_above_t',7); //to place image above title
function image_above_t() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0]; //path of first image occuring in the_content
if(!empty($first_img)) { //outputting the first image above title
?>
<div id="i_a_t">
<a href="<?php echo get_permalink( $post->ID ); ?>"><img src="<?php echo $first_img ?>" /></a>
</div>
<?php
}
else { //to simply provide a line gap if no image is present
?>
<br />
<?php
}
}
//to remove first image from the_content so that image dosen't occur twice in - above title and content as well
add_filter('the_content', 'remove_image_content',11);
function remove_image_content($content) {
if(!is_page()) { //fix to stop any unwanted change happening in page context
return preg_replace("/\< *[img][^\>]*[.]*\>/i","",$content,1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment