Skip to content

Instantly share code, notes, and snippets.

@helpercode0
Last active September 27, 2022 15:25
Show Gist options
  • Save helpercode0/eabbfa64b6b0712ba3a41aef85163b4e to your computer and use it in GitHub Desktop.
Save helpercode0/eabbfa64b6b0712ba3a41aef85163b4e to your computer and use it in GitHub Desktop.
How to setup wordpress default featured image
<?php
add_filter( 'get_post_metadata', 'WDFI_get_post_metadata', 50, 10);
function WDFI_get_post_metadata($null, $object_id, $meta_key, $single ){
if ( ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) ) {
return $null;
}
if ( ! empty( $meta_key ) && '_thumbnail_id' !== $meta_key ) {
return $null;
}
$post_type = get_post_type( $object_id );
if ( false !== $post_type && ! post_type_supports( $post_type, 'thumbnail' ) ) {
return $null;
}
$meta_cache = wp_cache_get( $object_id, 'post_meta' );
if ( ! $meta_cache ) {
$meta_cache = update_meta_cache( 'post', array( $object_id ) );
if ( ! empty( $meta_cache[ $object_id ] ) ) {
$meta_cache = $meta_cache[ $object_id ];
} else {
$meta_cache = array();
}
}
if ( ! empty( $meta_cache['_thumbnail_id'][0] ) ) {
return $null;
}
// add attachment id here
$default_thumbnail_id = 1;
$meta_cache['_thumbnail_id'][0] = $default_thumbnail_id;
wp_cache_set( $object_id, $meta_cache, 'post_meta' );
return $null;
}
add_filter( 'post_thumbnail_html', 'WDFI_post_thumbnail_html', 100, 10);
function WDFI_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
// add attachment id here
$default_thumbnail_id = 1;
if ( (int) $default_thumbnail_id !== (int) $post_thumbnail_id ) {
return $html;
}
if ( isset( $attr['class'] ) ) {
$attr['class'] .= ' gm-default-featured-img';
} else {
$size_class = $size;
if ( is_array( $size_class ) ) {
$size_class = 'size-' . implode( 'x', $size_class );
}$attr = array( 'class' => "attachment-{$size_class} default-featured-img" );
}
$html = wp_get_attachment_image( $default_thumbnail_id, $size, false, $attr );
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment