Automattic / Automattic/wp-super-cache
Use get_queried_object_id() as a more reliable way to get wp_cache_post_id()
- Dominant language
- PHP
- Stars
- 436
- Forks
- 130
- Avg merge
- 15h 11m
- Merged PRs (30d)
- 10
Description
On our site the `wp_cache_post_id` function is throwing an error:
`PHP Fatal error: Cannot use object of type WP_Query as array in public_html/wp-content/plugins/wp-super-cache/wp-cache-phase2.php on line 1278`
This is the function. It turns out that the way the things are setup, while `is_page()` is true, `$posts[0]->ID` does not contain the expected variable.
```
function wp_cache_post_id() {
global $posts, $comment_post_ID, $post_ID;
// We try hard all options. More frequent first.
if ($post_ID > 0 ) return $post_ID;
if ($comment_post_ID > 0 ) return $comment_post_ID;
if (is_single() || is_page()) return $posts[0]->ID;
if (isset( $_GET[ 'p' ] ) && $_GET['p'] > 0) return $_GET['p'];
if (isset( $_POST[ 'p' ] ) && $_POST['p'] > 0) return $_POST['p'];
return 0;
}
```
If I change the function by first checking `if(get_queried_object_id()) return get_queried_object_id();`, our page loads fine without throwing the fatal error:
```
function wp_cache_post_id() {
global $posts, $comment_post_ID, $post_ID;
// We try hard all options. More frequent first.
if(get_queried_object_id()) return get_queried_object_id();
if ($post_ID > 0 ) return $post_ID;
if ($comment_post_ID > 0 ) return $comment_post_ID;
if (is_single() || is_page()) return $posts[0]->ID;
if (isset( $_GET[ 'p' ] ) && $_GET['p'] > 0) return $_GET['p'];
if (isset( $_POST[ 'p' ] ) && $_POST['p'] > 0) return $_POST['p'];
return 0;
}
```
Update: it turns out that the theme we were using was incorrectly overwriting the `$posts` variable for a separate query. I fixed that, however I think updating `wp_cache_post_id()` to use `get_queried_object_id()` as a first resort would still be a good idea.
Contributor guide
No contributing guide indexed for this repository
Research direction
Read wp-cache-phase2.php around line 1278 and inspect wp_cache_post_id(), including how its existing fallbacks use $posts. Verify the WordPress query context that caused the reported WP_Query-as-array error, then confirm the function reliably returns the queried post ID without breaking its fallback behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php, wordpress
- Domain
- backend, performance
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100