Make WordPress Core

Opened 13 months ago

Last modified 13 months ago

#58147 new defect (bug)

bugfix: rewind_posts when posts array index != 0

Reported by: diogovf's profile diogovf Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 6.2
Component: Query Keywords: has-patch
Focuses: Cc:

Description

When the posts array doesn't start with the index 0, it generates an error due to hard code 0.

Before:

<?php
public function rewind_posts() {
    $this->current_post = -1;
    if ( $this->post_count > 0 ) {
        $this->post = $this->posts[0];
    }
}

After:

<?php
public function rewind_posts() {
    $this->current_post = -1;
    if ( $this->post_count > 0 ) {
        $this->post = $this->posts[array_key_first($this->posts)];
    }
}

Change History (4)

This ticket was mentioned in PR #4338 on WordPress/wordpress-develop by diogo-vf.


13 months ago
#1

  • Keywords has-patch added; needs-patch removed

Hi team,
The rewind_posts crashes when we have an object with posts that don't start at position 0. I use an api with more than 5 thousand objects and sometimes the posts start with an index greater than 0.

Trac ticket: 58147

#2 @Presskopp
13 months ago

This won't work as is with PHP < v7.3.0, see https://www.php.net/manual/en/function.array-key-first.php

Until now WordPress still claims compatibility to PHP v5.6.20, see https://wordpress.org/about/requirements/

#3 @petitphp
13 months ago

Hi, welcome to the trac, and thanks for the ticket and the associated PR.

As far as I can tell, the rewind_posts method hasn't changed since it was introduced in WP 1.5. Can you share more info on how you end up with a posts array that doesn't start at index 0 for your query ?

As noted by @Presskopp WordPress is still supporting PHP 5.6, you could use reset to achieve the same result while keeping this compatibility.

#4 @diogovf
13 months ago

Hi,
I've forgot the support for the old php versions, yeah I'll update this with reset, thanks @Presskopp and @petitphp.

I'vee a wordpress linked to an external API and when I receive posts sorted by the API. The final array may start with a larger ID like 1572 or 3518 because the WP_post object is built and sorted by the external API. I noticed the problem when I joined the project and the team overcame the problem by writing a wrapper to work around the error.

Note: See TracTickets for help on using tickets.