Skip to content

Instantly share code, notes, and snippets.

@ivanildodias
Last active October 1, 2015 21:22
Show Gist options
  • Save ivanildodias/535468b3f3c91d5649cb to your computer and use it in GitHub Desktop.
Save ivanildodias/535468b3f3c91d5649cb to your computer and use it in GitHub Desktop.
Retornar a primeira imagem do post [Get the first post image]
<?php
/**
* Retorna a tag <img> com a primeira imagem de um post. Caso o post não tenha imagens,
* retorna uma imagem padrão.
*/
function get_first_image( $args = array() ) {
global $post, $posts;
$args = wp_parse_args( $args, array(
'native_class' => true,
'class' => false,
'default_alt' => '',
'default_image' => get_template_directory_uri() . '/img/default.jpg',
'echo' => true
) );
$first_img = '';
$matches = '';
preg_match_all( '/<img .+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
$first_img = ( $matches[0] ) ? $matches[0][0] : false;
// Se não houver imagens
if ( empty( $first_img ) ) {
// Define uma imagem padrão
$img_atts = array();
$img_atts[] = 'src="' . esc_url( $args['default_image'] ) . '"';
$img_atts[] = ( empty( $args['default_alt'] ) ) ? 'alt="Post Image"' : 'alt="' . esc_attr( $args['default_alt'] ) . '"';
$img_atts[] = ( empty( $args['class'] ) ) ? '' : 'class="' . $args['class'] . '"';
$img_atts = join( ' ', array_filter( $img_atts ) );
$first_img = '<img ' . $img_atts . '/>';
} else {
if ( false === $args['native_class'] ) {
// Se já tiver alguma classe
if ( false !== strpos( $first_img, 'class=' ) ) {
$replace = ( false === $args['class'] ) ? '' : 'class="' . $args['class'] . '"';
$first_img = preg_replace( '/class="*"/i', $replace, $first_img );
} else {
$first_img = ( false === $args['class'] ) ? $first_img : str_replace( '<img', '<img class="' . $args['class'] . '"', $first_img );
}
} else {
// Se já tiver alguma classe
if ( false !== strpos( $first_img, 'class=' ) ) {
$replace = ( false === $args['class'] ) ? 'class="' : 'class="' . $args['class'] . ' ';
$first_img = str_replace( 'class="', $replace, $first_img );
} else {
$first_img = ( false === $args['class'] ) ? $first_img : str_replace( '<img', '<img class="' . $args['class'] . '"', $first_img );
}
}
}
if ( $args['echo'] ) {
echo $first_img;
} else {
return $first_img;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment