Last active
August 29, 2015 14:00
-
-
Save ericwenn/01cbe239902aed37e57c to your computer and use it in GitHub Desktop.
Get the most relevant image in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns the attachment id for the most relevant image of the post | |
* @author Eric Wennerberg | |
* @package Flavour | |
*/ | |
function get_relevant_image() { | |
if(has_post_thumbnail()) { | |
return get_the_featured_image_id(); | |
} else { | |
return get_the_first_image(); | |
} | |
} | |
/** | |
* Returns relevant image source | |
* @author Eric Wennerberg | |
* @package Flavour | |
* @param bool | str $size | |
*/ | |
function get_relevant_image_src($size = false) { | |
if(!$size): | |
$imageArray = wp_get_attachment_image_src(get_relevant_image()); | |
else: | |
$imageArray = wp_get_attachment_image_src(get_relevant_image(), $size); | |
endif; | |
return $imageArray[0]; | |
} | |
/** | |
* Returns the attachment id of the featured image | |
* @author Eric Wennerberg | |
* @package Flavour | |
* @return int | |
*/ | |
function get_the_featured_image_id() { | |
return get_post_thumbnail_id(get_the_ID()); | |
} | |
/** | |
* Returns the post's first image's id | |
* @author Eric Wennerberg | |
* @package Flavour | |
* @return int | |
*/ | |
function get_the_first_image() { | |
$output = preg_match_all('/wp-image-([0-9]*)/i', get_the_content(), $matches); | |
if(empty($matches[1])) { | |
return false; | |
} | |
return $matches[1][0]; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment