Skip to content

Instantly share code, notes, and snippets.

@willybahuaud
Last active October 18, 2016 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willybahuaud/30593cc1d3337c5c729790bb8aaf423d to your computer and use it in GitHub Desktop.
Save willybahuaud/30593cc1d3337c5c729790bb8aaf423d to your computer and use it in GitHub Desktop.
Set a default thumbnail
<?php
// To work, this function require to bypass has_post_thumbnail() test into templates…
add_filter( 'post_thumbnail_html', 'default_post_thumbnail_html', 10, 5 );
function default_post_thumbnail_html( $html, $post_ID, $post_thumbnail_id, $size, $attr ) {
// If no thumbnail is sendback by get_post_thumbail(), return a default image
if ( '' == $html && in_array( get_post_type( $post_ID ), array( 'post', 'page' ) ) ) {
// Get a default thumbnail ID into a list
$thumbs = get_option( 'options_default_thumbnails', array() );
$thumb = $thumbs[ array_rand( $thumbs ) ];
remove_filter( 'post_thumbnail_html', 'default_post_thumbnail_html', 10, 5 );
$html = wp_get_attachment_image( $thumb, $size, '', $attr );
add_filter( 'post_thumbnail_html', 'default_post_thumbnail_html', 10, 5 );
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment