Opened 7 weeks ago
Last modified 6 weeks ago
#65520 new enhancement
Improve type safety in get_the_ID() to prevent property access on non-WP_Post values
| Reported by: | salmanshafiq8630 | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | Awaiting Review |
| Component: | Posts, Post Types | Version: | 0.71 |
| Severity: | normal | Keywords: | has-patch reporter-feedback close |
| Cc: | Focuses: |
Description
get_the_ID() relies on get_post() and assumes that the returned value is always a valid WP_Post object. However, in certain edge cases (custom filters, early execution contexts, or when no global post is set), get_post() may return null, false, or a non-WP_Post value.
In such cases, the current implementation can lead to PHP warnings when attempting to access the ID property on a non-object.
Current implementation:
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
Problem:
empty( $post ) does not guarantee $post is a valid WP_Post instance.
If $post is null or another falsy non-object value, accessing $post->ID may trigger a warning:
Attempt to read property "ID" on null
Suggested improvement:
Use strict type checking to ensure $post is a valid WP_Post object before accessing properties.
function get_the_ID() {
$post = get_post();
if ( ! ( $post instanceof WP_Post ) ) {
return false;
}
return $post->ID;
}
Change History (5)
This ticket was mentioned in PR #12276 on WordPress/wordpress-develop by @salmanshafiq8630.
7 weeks ago
#1
#2
@
7 weeks ago
- Component General → Posts, Post Types
Per the PHP documentation, the empty() check returns true for all falsey values:
Returns true if var does not exist or has a value that is empty or equal to zero, aka falsey, see conversion to boolean. Otherwise returns false.
As neither get_post() or WP_Post::get_instance() don't have any developer filters, it is safe to assume a non-empty value is a WP_Post object.
@salmanshafiq8630 Is this something you are seeing in your server logs or a theoretical issue?
mojunaid8 commented on PR #12276:
7 weeks ago
#3
Good Idea
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
https://core.trac.wordpress.org/ticket/65520