[wp-trac] [WordPress Trac] #52386: Should WP_Query::get_posts be a private method?
WordPress Trac
noreply at wordpress.org
Wed Jan 27 21:57:25 UTC 2021
#52386: Should WP_Query::get_posts be a private method?
--------------------------+-----------------------------
Reporter: rebasaurus | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Query | Version:
Severity: normal | Keywords:
Focuses: performance |
--------------------------+-----------------------------
Sometimes, users call `WP_Query::get_posts()` incorrectly, as it is a
publicly accessible method:
{{{#!php
<?php
$args = [
// do args here
];
$my_query = new WP_Query( $args );
$my_posts = $my_query->get_posts();
}}}
Unfortunately, this ends up doing a double query to the DB, as the
`WP_Query::get_posts()` is mistaken for a getter when used outside the
scope of the constructor. The ideal way to efficiently query would be:
{{{#!php
<?php
$args = [
// do args here
];
$my_query = new WP_Query( $args );
$my_posts = $my_query->posts;
}}}
...Or in the case where no arguments are directly passed into a new
WP_Query:
{{{#!php
<?php
$args = [
// do args here
];
$my_query = new WP_Query;
$my_posts = $my_query->query( $args );
}}}
''I just want to preface that I actually don't have the historical context
behind why `WP_Query::get_posts()` remains a public method (whether it's
left for backwards-compatibility reasons or whatnot).''
@jrf suggests a potential approach to this in https://github.com/WordPress
/WordPress-Coding-Standards/issues/1860#issuecomment-768296206:
> it may be more appropriate to see if this can be solved in WP Core by
checking if the $query is the same as previously used and if so, short-
circuiting the function to return the previously retrieved results as
saved in the $posts property.
Would love to see some discussion around this if it can get resolved
within WP Core.
Thanks!
--
Ticket URL: <https://core.trac.wordpress.org/ticket/52386>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list