Skip to content

Instantly share code, notes, and snippets.

@cpaul007
Last active February 15, 2017 06:09
Show Gist options
  • Save cpaul007/0b3ed6e2fc9189ffcac92f0d6392c438 to your computer and use it in GitHub Desktop.
Save cpaul007/0b3ed6e2fc9189ffcac92f0d6392c438 to your computer and use it in GitHub Desktop.
Replacing the featured image with any other internal image of a post (only for category page)
<?php //* Remove this line
add_filter( 'genesis_get_image', 'gd_category_post_image', 10, 6 );
/**
* Replacing the featured image with any other internal image of post
* if there have more than one image and not set as featured image
*
* @author Chinmoy Paul
* @copyright Copyright (c) 2017, Genesis Developer
* @license GPL 3.0+
*/
function gd_category_post_image( $output, $args, $id, $html, $url, $src ) {
$feat_image_id = NULL;
//* Execute the code if you are on category page
if( is_category() ) {
//* get featured image ID if you have
if ( has_post_thumbnail() )
$feat_image_id = get_post_thumbnail_id( get_the_ID() );
//* Getting all attachments of a post
$attachments = get_posts( array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => get_the_ID()
) );
if( $attachments && count( $attachments ) > 1 ) {
foreach ( $attachments as $key => $attachment ) {
//* Excluding the featured image
if( ! empty( $feat_image_id ) && $feat_image_id == $attachment->ID )
continue;
//* Getting first or another image ID
$id = $attachment->ID;
break;
}
$html = wp_get_attachment_image( $id, $args['size'], false, $args['attr'] );
list( $url ) = wp_get_attachment_image_src( $id, $args['size'], false, $args['attr'] );
// Source path, relative to the root.
$src = str_replace( home_url(), '', $url );
// Determine output.
if ( 'html' === mb_strtolower( $args['format'] ) )
$output = $html;
elseif ( 'url' === mb_strtolower( $args['format'] ) )
$output = $url;
else
$output = $src;
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment