[wp-trac] [WordPress Trac] #41446: The PHP notice displayed after the overwriting global $posts by a new empty query.

WordPress Trac noreply at wordpress.org
Wed Jul 26 07:57:46 UTC 2017


#41446: The PHP notice displayed after the overwriting global $posts by a new empty
query.
-----------------------------+-----------------------------
 Reporter:  danielpietrasik  |      Owner:
     Type:  defect (bug)     |     Status:  new
 Priority:  normal           |  Milestone:  Awaiting Review
Component:  Query            |    Version:  4.8
 Severity:  normal           |   Keywords:
  Focuses:                   |
-----------------------------+-----------------------------
 '''Tested in WordPress 4.8, twentyseventeen theme with default
 configuration (just installed).'''

 After the overwriting a global variable {{{$posts}}} by a new
 {{{get_posts()}}} query (which return an empty array (no posts)) there is
 a PHP notice displayed:

 {{{
 Notice: Undefined offset: 0 in /.../wp-includes/class-wp-query.php on line
 3162
 }}}

 The overwriting is not a best choice, but some themes and plugins do it,
 so we should solve this problem.

 The problem is in {{{WP_Query}}} class in {{{rewind_posts()}}} method in
 {{{wp-includes/class-wp-query.php}}} file.

 '''The original method:'''

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

 '''The problem:''' the global query has at least one posts, but a new
 query has not. So the {{{$this->post_count}}} property is always positive,
 but the {{{$this->posts[0]}}} is not exists. In this step, the PHP notice
 is displayed.

 '''An example of solution:'''

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

 Right now the method checks that the query has posts and the first post is
 set and is not null.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/41446>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list