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 | 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)
#2
in reply to:
↑ description
@
4 years ago
- Severity changed from minor to normal
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
Replying to tomcent:
This is now line 106 after the WP 5.5 update.
The issue is still present on this version.