Skip to content

Instantly share code, notes, and snippets.

@dboutote
Created July 26, 2015 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dboutote/83b08f3032b111ef0385 to your computer and use it in GitHub Desktop.
Save dboutote/83b08f3032b111ef0385 to your computer and use it in GitHub Desktop.
Create/Load a default post thumbnail (WordPress theme)
<?php
/**
* Default Img for post thumbnails
*
* @param $file_name_new (string) Name of the newly-created file
* @param $file_name_orig (string) Filename of the original default image
* @param $post_id (int) ID of the associated Post
* @param $size (array) Width/height of cropped thumbnail
* @param $class (string) Optional class attribute for output image
* @param $show_link (bool) Truthy wraps IMG in permalink. Falsy does not.
*/
function get_default_post_thumbnail( $file_name_new = '', $file_name_orig = '', $post_id, $size, $class = '', $show_link = false ) {
$class = ('' != $class) ? 'class="' . $class . ' "': '';
if( '' === $file_name_new )
$file_name_new = 'img_default_thumb-';
if( '' === $file_name_orig )
$file_name_orig = 'img_default_thumb.png';
$thumb_path = get_stylesheet_directory() . '/img/'.$file_name_new . $size[0] . 'x' . $size[1] . '.png';
// check if thumbnail already exists
if ( !file_exists( $thumb_path ) ) {
$img_path = get_stylesheet_directory() . '/img/' . $file_name_orig;
if( file_exists( $img_path ) ) {
$image = wp_get_image_editor( $img_path );
if ( ! is_wp_error( $image ) ) {
$image->resize( $size[0], $size[1], true );
$image->save( $thumb_path );
$thumb_img = basename($thumb_path);
}
}
} else {
$thumb_img = basename($thumb_path);
}
$html = '<img ' . $class . ' src="' . get_stylesheet_directory_uri() . '/img/' . $thumb_img . '" />';
if ($show_link) {
$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '">' . $html . '</a>';
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment