Make WordPress Core

Opened 4 years ago

Last modified 5 days ago

#50847 new defect (bug)

update_post_thumbnail_cache returns notice when get_the_post_thumbnail used with ID after setup_postdata()

Reported by: tomcent's profile tomcent Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 5.4.2
Component: Post Thumbnails Keywords: has-patch
Focuses: Cc:

Description

Situation:

  • Inside main loop
  • foreach over array of (related) post_id's,
  • use setup_postdata($post) for each item
  • Items call get_template_part(something)
  • Template parts uses get_the_post_thumbnail which allow a post_ID
  • get_the_post_thumbnail calls update_post_thumbnail_cache (because in_the_loop)
  • update_post_thumbnail_cache gives notice on line 101: Trying to get property 'ID' of non-object
  • Restore main loop with wp_reset_postdata()

Possible fix:
Change this

<?php
foreach ( $wp_query->posts as $post ) {
        $id = get_post_thumbnail_id( $post->ID );
        if ( $id ) {
                $thumb_ids[] = $id;
        }
}

To this

<?php
foreach ( $wp_query->posts as $post ) {
        if (is_object($post)) {
                $post = $post->ID;
        }
        $id = get_post_thumbnail_id( $post );
        if ( $id ) {
                $thumb_ids[] = $id;
        }
}

in /wp-includes/post-thumbnail-template.php line 101

Change History (3)

#1 @SergeyBiryukov
4 years ago

  • Component changed from General to Post Thumbnails

#2 in reply to: ↑ description @tomcent
4 years ago

  • Severity changed from minor to normal

Replying to tomcent:

update_post_thumbnail_cache gives notice on line 101: Trying to get property 'ID' of non-object

Change in /wp-includes/post-thumbnail-template.php line 101

This is now line 106 after the WP 5.5 update.
The issue is still present on this version.

This ticket was mentioned in PR #7954 on WordPress/wordpress-develop by @geekofshire.


5 days ago
#3

  • Keywords has-patch added; needs-patch removed

This PR addresses an issue where notices such as "Trying to get property 'ID' of non-object" could occur when working with $wp_query->posts in loops. The code has been updated to validate that $post is an instance of WP_Post before attempting to access its properties. If $post is valid, it is converted to its post ID to ensure compatibility with get_post_thumbnail_id(). This change prevents errors in scenarios where $post may not be a proper object, improving the reliability and stability of the loop when handling post data.

Trac ticket: https://core.trac.wordpress.org/ticket/50847

Note: See TracTickets for help on using tickets.