[wp-trac] [WordPress Trac] #23983: Add filter to get_post_thumbnail_id to override default thumbnail use

WordPress Trac noreply at wordpress.org
Tue Aug 28 22:29:51 UTC 2018


#23983: Add filter to get_post_thumbnail_id to override default thumbnail use
-------------------------------------------------+-------------------------
 Reporter:  Jesper800                            |       Owner:
                                                 |  SergeyBiryukov
     Type:  enhancement                          |      Status:  reviewing
 Priority:  normal                               |   Milestone:  5.0
Component:  Media                                |     Version:
 Severity:  normal                               |  Resolution:
 Keywords:  2nd-opinion needs-testing has-patch  |     Focuses:
-------------------------------------------------+-------------------------

Comment (by SergeyBiryukov):

 Replying to [comment:9 leogermani]:
 > hooking in get_%type%_metadata is messy, because you can not easily
 check wether the post has a post thumbnail or not inside your filter, you
 would end up in an endless loop if you call has_post_thumbnail()

 You can avoid an endless loop by removing and re-adding the filter:
 {{{
 function wp23983_get_featured_image_id( $null, $object_id, $meta_key,
 $single ) {
         if ( '_thumbnail_id' !== $meta_key ) {
                 return $null;
         }

         if ( is_admin() ) {
                 return $null;
         }

         remove_filter( 'get_post_metadata', __FUNCTION__, 10, 4 );

         $featured_image_id = get_post_thumbnail_id( $object_id );

         add_filter( 'get_post_metadata', __FUNCTION__, 10, 4 );

         // The post has a featured image.
         if ( $featured_image_id ) {
                 return $featured_image_id;
         }

         // Do something else
         ...

         return $featured_image_id;
 }
 add_filter( 'get_post_metadata', 'wp23983_get_featured_image_id', 10, 4 );
 }}}
 I agree it's not pretty though, and a filter would be helpful.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/23983#comment:12>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list