0

I've 3 different post types and want to set the default featured image for each post type. Thank you in advance.

New contributor
Aryan Chaurasia is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

You could filter the get_post_meta() function and provide different attachment IDs based on the post type. This could be built as a stand-alone plugin or added to a theme ( or Child Theme ) functions.php file. It could also be extended to retrieve option values set by the user. The following example is a static ID associated which would be associated with an uploaded attachment.

/**
 * Provide a default Attachment ID for Featured Images
 * 
 * @param NULL $value
 * @param Integer $post_id
 * @param String $meta_key
 * @param Boolean $single
 * @param String $meta_type
 * 
 * @return Integer $value|NULL
 */
function default_post_thumbnail( $value = null, $post_id, $meta_key, $single, $meta_type ) {
    
    // Prevent default images from displaying in admin
    if( '_thumbnail_id' !== $meta_key || is_admin() ) {
        return $value;
    }
    
    /**
     * Removing and re-adding the filter is important to prevent an infinite loop.
     * When any function calls `get_post()` it calls `get_post_metadata()`.
     * The following functions call `get_post()` internally.
     */
    remove_filter( 'get_post_metadata', __FUNCTION__, 10 );
        $post_type          = get_post_type( $post_id );
        $post_thumbnail_id  = get_post_thumbnail_id( $post_id );
    add_filter( 'get_post_metadata', __FUNCTION__, 10, 5 );
    
    // We have a Post Thumbnail ID - Return it.
    if( $post_thumbnail_id ) {
        return $post_thumbnail_id;
    }
    
    switch( $post_type ) {
        case 'post':
            $value = 123;   // WordPress Attachment ID of some kind.
            break;
    }
    
    return $value;
    
}
add_filter( 'get_post_metadata', 'default_post_thumbnail', 10, 5 );

Your Answer

Aryan Chaurasia is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.