__group__,ticket,summary,owner,_component,_version,priority,severity,milestone,type,_status,workflow,_created,modified,_description,_reporter
Tickets Awaiting Review,43372,$wp_query->max_num_pages return value as float,,Query,4.9.4,normal,trivial,Awaiting Review,defect (bug),new,,2018-02-20T16:32:40Z,2022-02-10T15:13:40Z,"As a page number, Integer would make more sense than Float.
This is not a big problem but kinda annoying when you do strict comparison on this value. since no one will define a page number as float.",ironghost63
Tickets Awaiting Review,39914,'orderby' date results differs depend on 'post_status',,Query,4.7.2,normal,normal,Awaiting Review,defect (bug),new,,2017-02-19T09:40:43Z,2017-02-19T09:40:43Z,"Default 'orderby' date return different order results depend on 'post_status' passed in WP_Query.
For example, 3 published posts with identical post_date (if bulk publish, import or other stuff) in WP_Query will return different posts order on page, which depend on 'post_status' = 'publish' or 'any'.
Since all posts are published, setting 'post_status' should not affect default orderby date results. Most notably this difference in edit.php?post_type= in comparison with front-end WP_Query results.
Is it normal behaviour of such querying results?",esemlabel
Tickets Awaiting Review,55649,Block Query with full post content do not display properly,,Query,5.9.3,normal,normal,Awaiting Review,defect (bug),new,,2022-05-02T12:15:53Z,2022-05-02T12:15:53Z,"When i change the QueryBlock content from the post excerpt to full post content in block theme edditor i get the correct behaviour but on the website it will not display the correct post content
i think it's not inheriting the query from the queryBlock and it is taking the query parameters from the main page instead.",jawedzennaki
Tickets Awaiting Review,56165,Bogus query parameters force WordPress to drop query limit and exhausts memory,,Query,6.0,normal,normal,Awaiting Review,defect (bug),new,,2022-07-06T18:30:28Z,2022-07-06T18:33:37Z,"I noticed that a site was regularly getting out of memory errors at a URL that seems to be an attempt at ""hacking"" a Drupal site:
{{{
https://example.com/?q=user%2Fpassword&name[%23post_render][]=passthru&name[%23type]=markup&name[%23markup]=dir&debug
}}}
For some reason this causes WordPress to execute this query:
{{{
SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC
}}}
You'll notice that there is no `LIMIT` set, even though the site has a limit set by default and there are no plugins/filters to alter this.
On a site with a large number of posts this can easily cause memory issues (I noticed it during the `update_meta_cache` function running after the query.
That URL is causing WordPress to execute this query:
{{{
WP_Query->query(Array ([name] => Array ([#post_render] => Array ([0] => passthru),[#type] => markup,[#markup] => dir)))
}}}
The `name` parameter is supposed to be a string, so I'm not sure why it's affecting the query at all (PHP 7.4 does throw warning because WP tries to `trim()` the value, PHP 8.1 throws error).
I haven't gotten far enough in to see why the query limit is dropped, but I imagine in any case this URL should result in either the homepage being displayed or a 404.
Here is a full backtrace:
{{{
#0 update_meta_cache(post, Array ([0] => 81102,[1] => 80934,[2] => 80927,...))
#1 update_postmeta_cache(Array ([0] => 81102,[1] => 80934,[2] => 80927,...))
#2 update_post_caches(Array ([0] => WP_Post Object ([ID] => 81102,[post_author] => 5,[post_date] => 2022-07-01 10:17:29,[post_date_gmt] => 2022-07-01 17:17:29,[post_content] =>
#3 WP_Query->get_posts() called at [/wp-includes/class-wp-query.php:3586]
#4 WP_Query->query(Array ([name] => Array ([#post_render] => Array ([0] => passthru),[#type] => markup,[#markup] => dir))) called at [/wp-includes/class-wp.php:648]
#5 WP->query_posts() called at [/wp-includes/class-wp.php:775]
#6 WP->main() called at [/wp-includes/functions.php:1330]
#7 wp() called at [/wp-blog-header.php:16]
#8 require(/wp-blog-header.php) called at [/index.php:4]
}}}",coreyw
Tickets Awaiting Review,28568,Can't get private posts/pages via WP_Query when not logged in as administrator,,Query,3.9,normal,normal,Awaiting Review,defect (bug),reopened,,2014-06-17T18:44:59Z,2019-03-22T14:10:01Z,"I want to use WP_Query to display content of one private page on some place in a template.
{{{
// ... theme template sidebar.php, for example
25, 'post_status' => 'private' )); // page #25 is set to ""private""
if ($the_query->have_posts())
{
// ... nope, no posts for you today
while ($the_query->have_posts())
{
$the_query->the_post();
the_content();
}
wp_reset_postdata();
}
?>
}}}
But it only works when I am logged in as administrator.
When I am not logged in, and print_r() the $the_query, there is ""request"" index filled with:
{{{SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.ID = 25 AND wp_posts.post_type = 'page' AND ((wp_posts.post_status = 'private')) ORDER BY wp_posts.post_date DESC}}}
Querying database with it directly in PHPMyAdmin, it returns one row as expected (page ID 25 row). But template loop does not anything. ""Posts"" index in $the_query is empty.
I have expected WP_Query works like ""just give me anything I want (defined by the arguments)"" ... and I want page with ID 25. ",mklusak
Tickets Awaiting Review,58200,Empty result when meta_query is supposed to select date less than certain date,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2023-04-26T17:53:16Z,2023-11-10T09:04:06Z,"
{{{
$args = [
'post_type' => 'page',
'posts_per_page' => '10',
'paged' => '1',
'meta_query' => [
'event' => [
'key' => 'event_end',
'value' => date( 'Y-m-d H:i:s' ),
'compare' => '<',
'type' => 'DATETIME'
],
];
}}}
Request will be:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE 1=1 AND (
( wp_postmeta.meta_key = 'event_end' AND CAST(wp_postmeta.meta_value AS DATETIME) < '2023-04-26 17:12:15' )
) AND wp_posts.post_type = 'page' AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY CAST(wp_postmeta.meta_value AS DATETIME) DESC
LIMIT 0, 10
}}}
And as a result, empty values will be among the result.
How to check:
1. Add to certain post_type post_meta event_end with empty value.
2. Create new WP_Query with this post_type and meta_query where event_end is less than current date (look above).
3. Get post and check that selection has empty value.
Expected behaviour is to get all posts, where event_end post_meta has a type of DATETIME and not empty.",oglekler
Tickets Awaiting Review,40903,Filtered posts_request query can break found_posts query,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2017-06-01T16:54:45Z,2017-06-01T18:40:57Z,"Suppose the `posts_request` query is built with `SQL_CALC_FOUND_ROWS`. The stage is set for `WP_Query::set_found_posts` issue `SELECT FOUND_ROWS()` because `$limits` is non-empty.
Now suppose a plugin filters `posts_requests` to the empty string because it gets results another way. WP_Query will still go ahead and issue `SELECT FOUND_ROWS()` erroneously.
Some plugins avoid this by filtering `found_posts_query` to the empty string. However, it seems like there is a better way to write the logic of `set_found_posts` so that it respects the filtered `posts_request` query and avoids the problematic statement: simply check the filtered query for `SQL_CALC_FOUND_ROWS` instead of looking at `$limits`.
Proposed fix:
{{{
private function set_found_posts( $q, $limits ) {
global $wpdb;
// Bail if posts is an empty array. Continue if posts is an empty string,
// null, or false to accommodate caching plugins that fill posts later.
if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
return;
- if ( ! empty( $limits ) ) {
+ if ( substr( $this->request, 0, 26 ) === 'SELECT SQL_CALC_FOUND_ROWS' ) ) {
/**
* Filters the query to run for retrieving the found posts.
*
}}}",andy
Tickets Awaiting Review,60395,Filtering posts by open ping_status returns posts with closed ping_status,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2024-01-31T07:06:00Z,2024-01-31T10:50:47Z,"CLI command {{{wp post --ping_status=open}}} returns published sticky posts with a {{{ping_status}}} of {{{closed}}}.
{{{
wp post list --ping_status=open --fields=ID,post_status,post_type,ping_status
+------+-------------+-----------+-------------+
| ID | post_status | post_type | ping_status |
+------+-------------+-----------+-------------+
| 2521 | publish | post | closed |
| 2508 | publish | post | closed |
+------+-------------+-----------+-------------+
}}}
The same command with a different output format yields no results:
{{{
wp post list --ping_status=open --format=ids
(no output)
}}}
Setting an arbitrary {{{ping_status}}} still returns results;
{{{
wp post list --ping_status=foobar --fields=ID,post_status,post_type,ping_status
+------+-------------+-----------+-------------+
| ID | post_status | post_type | ping_status |
+------+-------------+-----------+-------------+
| 2521 | publish | post | closed |
| 2508 | publish | post | closed |
+------+-------------+-----------+-------------+
}}}
The command should return no results as there are no posts with {{{ping_status}}} of {{{open}}}. At the very least, the results output should be consistent regardless of format.
Environment
{{{
OS: Linux 4.18.0-513.9.1.el8_9.x86_64 #1 SMP Wed Nov 29 18:55:19 UTC 2023 x86_64
Shell: /bin/bash
PHP binary: /usr/bin/php
PHP version: 8.1.27
php.ini used: /etc/php.ini
MySQL binary: /bin/mysql
MySQL version: mysql Ver 15.1 Distrib 10.5.22-MariaDB, for Linux (x86_64) using EditLine wrapper
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /var/www
WP-CLI packages dir:
WP-CLI cache dir: /home/deploy/.wp-cli/cache
WP-CLI global config:
WP-CLI project config: /var/www/wp-cli.yml
WP-CLI version: 2.9.0
}}}
GitHub issue:
https://github.com/wp-cli/entity-command/issues/453
",jamieburchell
Tickets Awaiting Review,59809,"Inconsistent ""ITEMS PER PAGE"" across pagination pages in the Query Loop",,Query,,normal,normal,Awaiting Review,defect (bug),new,,2023-11-06T02:11:45Z,2024-02-21T13:47:33Z,"There is an inconsistent behavior of the ""ITEMS PER PAGE"" across pagination pages in WP 6.4 and TT4 the Query Loop block.
Here is how to replicate it:
1. Ensure you have WP 6.4-RC3 installed, and the TT4 activated.
2. Ensure you have at least 10 blog posts.
3. Make a certain blog post sticky.
4. Navigate under Appearance > Editor, and edit any template.
5. In the template, add the Query Loop block, and choose a pattern that has pagination on it.
6. Disable the ""Inherit query from template"", and ensure the ""STICKY POSTS"" is set to include. Also, ensure the ""ORDER BY"" is set to ""Newest to Oldest""
7. From the ""Display Settings"" of the block, set the ""ITEMS PER PAGE"" to 2.
8. Save the changes, and come back to the frontend.
9. You will see that it shows 3 posts in the Query Loop, which is expected as it includes the Sticky post as well.
10. Now, navigate to the 2nd page using the pagination. See, now you will see 2 posts. This includes the STICKY post and another post.
11. Now, navigate to the 3rd page using the pagination. See, now you again have 3 posts showing, which is expected.
This is causing an issue with the 2nd page of the pagination, which is only showing 2 posts, including the Sticky one. But all the other pagination pages are showing fine, with 3 posts each, including the Sticky one. This is occurring in WP 6.4 and with the TT4 theme.",rajinsharwar
Tickets Awaiting Review,47493,Meta Query Sorting with relation => OR not behaving as expected,,Query,4.8.2,normal,normal,Awaiting Review,defect (bug),new,,2019-06-06T13:45:36Z,2019-06-06T14:18:32Z,"When sorting on multiple meta query clauses with the default AND relation the sorting works as expected. When sorting with an OR relation the sorting does not function as expected.
{{{
'meta_query' => array(
//'relation' => 'OR',// when turning this on the sorting does not work..
'cornerstone_clause' => array(
'key' => '_yst_is_cornerstone',
'compare' => 'EXISTS',
'type' => 'BINARY',
),
'count_clause' => array(
'key' => 'erp_post_views_count',
'compare' => '>',
'value' => 0,
'type' => 'NUMERIC',
),
),
'orderby' => array(
'cornerstone_clause' => 'DESC',
'count_clause' => 'DESC',
),
}}}
The idea of the query is to first show any posts that contain '_yst_is_cornerstone' and sort the remaining by 'erp_post_views_count'.",tcaneeaglepub
Tickets Awaiting Review,37251,Not return 404 on front-page with option page and url `/page/2`,,Query,4.5.3,normal,normal,Awaiting Review,defect (bug),new,,2016-07-01T15:31:11Z,2023-05-28T15:33:44Z,"If i setup page on front-page(Go `Settings`->`Reading`->`Set show on front static page and choose own page`->`Save`). Then go to front page on my site (example http://my-domain/) i see page, which setted before. But if i try open `http://my-domain/page/2`, `http://my-domain/page/3` and etc, i get always front-page, except i am wait 404 error. After debug i found solution (line 1777 in `query.php`):
{{{#!php
is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') && !$this->is_paged) {
$_query = wp_parse_args($this->query);
// pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
if ( isset($_query['pagename']) && '' == $_query['pagename'] )
unset($_query['pagename']);
unset( $_query['embed'] );
if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
$this->is_page = true;
$this->is_home = false;
$qv['page_id'] = get_option('page_on_front');
// Correct for page_on_front
if ( !empty($qv['paged']) ) {
$qv['page'] = $qv['paged'];
unset($qv['paged']);
}
}
}
}}}
Add `&& !$this->is_paged` check.",sheo13666q
Tickets Awaiting Review,40397,PHP 7.1.x problem in WP_Query,,Query,4.7.3,normal,normal,Awaiting Review,defect (bug),new,,2017-04-08T23:08:20Z,2018-01-11T03:59:56Z,"I believe I have found another instance of the defect reported in Trac #37772. This was reported in my plugin's support forum:
https://wordpress.org/support/topic/warning-parameter-2-to-mlaquery
The first post there includes the PHP message:
Warning: Parameter 2 to MLAQuery::mla_query_posts_search_filter() expected to be a reference, value given in /home/prodport/staging/1/wp-includes/class-wp-hook.php on line 298
A later post from @adrianb includes a call trace showing the call to `apply_filters()` from line 1995 in WP_Query.",dglingren
Tickets Awaiting Review,40984,Possible Bug with Named Orderby Meta Query SQL,,Query,4.8,normal,normal,Awaiting Review,defect (bug),new,,2017-06-09T19:51:56Z,2017-06-09T20:10:26Z,"I don't know how easy this would be to replicate, but I can at least walk through the steps in identifying the bug, and how I was able to address it for my own use-case.
On the web application we're building, we've added a simple meta field called ""spotlight"" to basically drive a single post to the front of the list, and apply some extra styling.
To do this, I had built the following query:
{{{#!php
'post',
'posts_per_page' => 3,
'orderby' => 'has_spotlight post_date',
'meta_query' => [
'relation' => 'OR',
'has_spotlight' => [
'key' => 'spotlight',
'value' => '1'
],
'standard' => [
'key' => 'spotlight',
'compare' => 'NOT EXISTS'
]
],
'tax_query' => [
[
'taxonomy' => 'post_tag',
'field' => 'name',
'terms' => 'News'
]
]
]);
}}}
In other areas of the web application, similar queries appeared to function as expected - the ""spotlight"" post would appear first in the list, with remaining posts ordered by date.
However, for the above query, something interesting happened: A post with no spotlight metadata was appearing at the top of the list, and the actual spotlight post was appearing below it.
Using PHPStorm and Xdebug, I set a breakpoint for the query and examined the object. Under the request property, the following SQL was generated:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
LEFT JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
LEFT JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id AND mt1.meta_key = 'spotlight' )
WHERE 1=1
AND (
wp_term_relationships.term_taxonomy_id IN (724)
)
AND (
( wp_postmeta.meta_key = 'spotlight' AND wp_postmeta.meta_value = '1' )
OR
mt1.post_id IS NULL
)
AND wp_posts.post_type = 'post'
AND (
wp_posts.post_status = 'publish'
OR
wp_posts.post_status = 'acf-disabled'
)
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order, CAST(wp_postmeta.meta_value AS CHAR) DESC, wp_posts.post_date DESC
LIMIT 0, 3
}}}
When running this SQL directly in SequelPro, the following IDs were returned, confirming the order that I was seeing:
1
227 <-- Spotlight Post ID
225
After looking through the SQL statement, I decided to check exactly what Wordpress was seeing. After modifying the query to include everything from the wp_postmeta query, something interesting happened:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID, wp_postmeta.* FROM wp_posts
...
}}}
I receive the following results:
{{{
ID meta_id post_id meta_key meta_value
1 51 1 _edit_lock 1496942377:1
227 20794 227 spotlight 1
225 3305 225 _yst_is_cornerstone
}}}
It appears that the table that's being used to define the ordering - '''wp_postmeta''' - is not being filtered the same way as the other table alias '''mt1'''.
Upon changing the order clause to use the filtered meta table:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID, mt1.*
...
CAST(mt1.meta_value AS CHAR) DESC
}}}
I received the correct results:
{{{
ID meta_id post_id meta_key meta_value
227 20794 227 spotlight 1
225 NULL NULL NULL NULL
1 NULL NULL NULL NULL
}}}
This is strange to me, as this line should theoretically prevent other unrelated meta information from being included in the results:
{{{
WHERE
...
( wp_postmeta.meta_key = 'spotlight' AND wp_postmeta.meta_value = '1' )
OR
mt1.post_id IS NULL
...
}}}
It should be noted that simply changing the ORDER BY clause in my case - while it ""fixes"" the issue - is not technically correct.
Instead, the primary meta query clause should also contain the same filtering that the second does. The complete query looks like so:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
LEFT JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'spotlight' )
LEFT JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id AND mt1.meta_key = 'spotlight' )
WHERE 1=1
AND (
wp_term_relationships.term_taxonomy_id IN (724)
)
AND (
( wp_postmeta.meta_key = 'spotlight' AND wp_postmeta.meta_value = '1' )
OR
mt1.post_id IS NULL
)
AND wp_posts.post_type = 'post'
AND (
wp_posts.post_status = 'publish'
OR
wp_posts.post_status = 'acf-disabled'
)
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order, CAST(wp_postmeta.meta_value AS CHAR) DESC, wp_posts.post_date DESC
LIMIT 0, 3
}}}
'''Notice that the first metadata left join contains the same filtering by meta_key as the second.'''
I'm not sure what far-reaching consequences this might have, or if this issue has come up in the past. I imagine it's a bit of an edge-case.
Let me know if this is something that you're able to reproduce on your end, or if you need more information in regards to this.",maiorano84
Tickets Awaiting Review,60027,Post patterns show no posts,,Query,,normal,major,Awaiting Review,defect (bug),new,,2023-12-07T09:14:28Z,2023-12-07T09:14:28Z,Newly created patterns for posts give 'no post found error' and create 'one post' of their own.,bferonia
Tickets Awaiting Review,42732,Problem with usage of WP_Term_Query inside WP_Tax_Query,,Query,4.9,normal,normal,Awaiting Review,defect (bug),new,,2017-11-28T15:15:21Z,2017-11-28T15:15:21Z,"This problem started on WP 4.9 because of #37038.
In WPML plugin, we filter the tax queries in order to convert the term IDs to their translations in the current language (if any).
In WP 4.8.3, `WP_Tax_Query::transform_query` was making direct calls to the DB.
In WP 4.9, `WP_Tax_Query::transform_query` is using `WP_Term_Query` to fetch the terms of the meta query.
The problem is that we have filters on `WP_Term_Query` (on `get_terms_args`) which applies to this.
This is usually not a problem, except for a post query with tax queries and `suppress_filters` set to `true`.
Here's an example:
{{{
$args = array(
'post_type' => 'post',
'suppress_filters' => true,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => [ 3, 4 ] // 3 is the English category and 4 is the translation in French
),
)
);
$wp_query = new WP_Query( $args );
}}}
'''What is expected (and actual behavior in 4.8.3):''' This query should return all the posts attached to the category 3 or 4, whatever the current language.
'''What we have now:''' The query returns the posts attached to 3 OR the posts attached to 4 (depending on the current language).
So we need a way to flag that `WP_Term_Query` is used inside `WP_Query` (via `WP_Tax_Query`) and `suppress_filters` is set to `true`.",strategio
Tickets Awaiting Review,48020,Queries display in inconsistent order when ordering by meta_value_num,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2019-09-11T17:00:10Z,2019-09-11T18:22:09Z,"So I caught this the other day. When ordering a query by
{{{meta_value_num}}}, multiple posts sharing the same meta value display in a random order such that if you run two identical queries, the order of the posts could differ between the two.
Example use case. I have a custom {{{class}}} post type with a {{{date}}} post meta. Many classes share the same date. On the frontend, I am displaying 12 classes at a time, ordered by date, and when users select to load more I fetch more posts from the server with and query more classes with
{{{'offset' => $classes_showing}}} and {{{'orderby' => 'meta_value_num'}}}. Classes belonging to the same show up in different orders from query to query, which occasionally results in multiple classes shown on the frontend.
Hopefully that was clear enough. Let me know if you need more code. Thanks.",truheart
Tickets Awaiting Review,56081,Query Loop block with selection causes Sticky Posts setting to be ignored,,Query,6.0,normal,normal,Awaiting Review,defect (bug),new,,2022-06-27T21:06:32Z,2022-06-27T21:06:32Z,"The Query Loop has an option to ""Inherit query from template"". There is another option to display Sticky posts - only, include, or exclude. On an Archive page where a query has pre-selected taxonomy, the sticky selector is ignored. So, where Inherit Query is checked, it doesn't matter if Sticky Posts is set to Include, Exclude, or Only - stickies and non-stickies are both always shown. The correct selection is shown in the template editor, but not when rendering an archive page from the front-end.
**To test:** I am getting my stickies up top and everything following by using two query loops in the default Home page that displays all blog posts.
In the Home template: This page is not filtered. The first query loop has Inherit Query unchecked, and Sticky Posts set to Include. The second query loop has Inherit Query unchecked, and Sticky Posts set to EXclude. So there are two loops, one for stickies, and the next for all others. This results here are as expecteed.
To achieve the same results as above for the Archive template, which is filtered. The two query loops would be set the same as above, except with Inherit Query checked in both. But the result is not as expected.
Let's try a simpler version for the Archive. One Query Loop has Inherit Query checked, and Sticky Posts set to Exclude or Only. The Sticky setting is ignored and all pre-selected posts are rendered in the archive page with stickies and non-stickies mixed. Again, it looks OK on the back-end, not on the front-end.
**Desired behavior:** The Sticky setting and anything else that can be configured for a Query Loop should be included in the query at run-time.
**Notes:**
- This might be specific to the Twenty TwentyTwo theme.
- I have not checked to see if the behavior is the same with the classic loop, without blocks, with PHP templates rather than HTML templates.",Starbuck
Tickets Awaiting Review,60274,Query loop showing too many posts,,Query,6.4.2,normal,normal,Awaiting Review,defect (bug),new,,2024-01-17T14:26:37Z,2024-01-17T14:35:11Z,"With recent updates, the query loop shows 4 posts while in editor (per the settings) but shows 5 in the site itself. (see mcld.org home page towards the bottom)",jcoonrod
Tickets Awaiting Review,57767,SQL query error with multiple order specifications in pre_get_posts.,,Query,6.1.1,normal,critical,Awaiting Review,defect (bug),new,,2023-02-20T03:09:37Z,2023-02-21T02:27:55Z,"https://ja.wordpress.org/support/topic/pre_get_posts%e3%81%a7%e8%a4%87%e6%95%b0%e3%81%ae%e4%b8%a6%e3%81%b3%e9%a0%86%e6%8c%87%e5%ae%9a%e3%81%a7%e3%82%a8%e3%83%a9%e3%83%bc/#post-11682395
We have started a thread in the above forum but have not been able to resolve the issue.
You can refer to the URL for more details, but when I specify multiple sorting conditions based on the value of a custom field, the results are not displayed properly, and when I throw the query portion of the request in $query directly to SQL in the hook point of pre_get_posts, the following error is returned The following error is returned.
{{{
Expression #1 of ORDER BY clause is not in GROUP BY clause and contains non-aggregated column 'local.wp_postmeta.meta_value' which is not functionally dependent on columns in the GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
}}}
{{{
}}}
Is this part of a bug?",kuroro111
Tickets Awaiting Review,46285,Search colums of WP User Query vars is not updated after applying user_search_columns filter,,Query,4.9.8,normal,trivial,Awaiting Review,defect (bug),new,,2019-02-20T08:21:54Z,2019-02-20T08:21:54Z,"While preparing the query variables of WP_User_Query , it appears that, after applying user_search_columns filter, the possibly modified array search_columns in WP_User_Query->query_vars argument is not updated .",wonderyan
Tickets Awaiting Review,45376,Search not working as described in codex,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2018-11-19T13:07:01Z,2018-12-07T01:56:14Z,"In the codex it says if I sort my search query results by relevance it should behave as follows:
""Order by search terms in the following order: First, whether the entire sentence is matched. Second, if all the search terms are within the titles. Third, if any of the search terms appear in the titles. And, fourth, if the full sentence appears in the contents.""
That actually is not right, because the third case never happens! Example:
I have 3 Posts with titles: ""Keyword"", ""Key"" and ""Word""
If I search for ""?s=key+word"" the result ist only ""Keyword"" but it should be ""Key"" and ""Word"" too!?",totatari
Tickets Awaiting Review,54853,Search only searching phrases and not searching individual terms,,Query,5.8.3,normal,normal,Awaiting Review,defect (bug),new,,2022-01-19T03:00:51Z,2022-01-19T07:46:09Z,"
{{{
get_posts(array(
""post_type"" => ""fruit"",
""s"" => ""apple orange banana""
));
}}}
should search for each term separately, but it does not. It searches the entire string as a phrase.
Issue is within /wp-includes/class-wp-query.php line 1398. It's a simple change:
{{{
$searchand = ' AND ';
to
$searchand = ' OR ';
}}}
",jchang
Tickets Awaiting Review,50885,Setting a pre_get_posts query post_type to array results in broken wp-admin filters,,Query,5.4.2,normal,normal,Awaiting Review,defect (bug),new,,2020-08-10T12:46:14Z,2020-08-11T01:27:00Z,"I have a in-house plugin which creates a few extra alternate post types (eg. `post_custom`), and one of its requirements is that these post types are queried together with normal posts.
To do this, I've implemented a function which converts any queries for the `post` post type into `array( 'post', 'post_custom', ... )` and it works as it should, but when on wp-admin, if one tries to go into the default ""Posts"" menu and filter by author or even search for anything, it will return a message saying ""Invalid post type"".
Checking the URL, it will contain the `post_type` query string as ""Array"" instead of ""post"", and changing it manually to ""post"" fixes the issue. I guess the wp-admin interface is not handling the array of post types correctly?",matpratta
Tickets Awaiting Review,54436,Sorting issue- when sorting via a custom meta key,,Query,5.5.2,normal,normal,Awaiting Review,defect (bug),new,,2021-11-13T12:38:27Z,2021-11-14T18:01:55Z,"So, I created a new meta key with the name `_tstock` and stored numeric values in it, used the code below for sorting:
{{{
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = '_tstock';
}}}
The products tend to repeat after switching the page if the value of `_tstock` of the last product is similar to first product on the next page.
Elaborating a bit more :-
Let's assume that there are 10 products with the `_tstock` value equal to one and 5 products are displayed on the first page while the rest 5 are displayed on second page.
The total number of the product will not change instead some of the products from the first page will be displayed on the second page replacing the ones that should be displayed.",prashantinfozion
Tickets Awaiting Review,39140,Taxonomies - operator AND doesn't work properly for taxonomy hierarchies,,Query,4.6.1,normal,normal,Awaiting Review,defect (bug),new,,2016-12-07T08:54:32Z,2019-01-08T19:56:52Z,"Hi,
This is a problem discovered using WooCommerce shortcodes but has its core problem in the WP core according to my findings. I've already implemented a fix for this in a customer project.
I’ve ran into problems using one of the Woo shortcodes and operator ‘AND’. This is questioned by others several times before (see links below) but it seems like the core of the problem is not solved. I’ve worked with the issue on WP 4.6.1 installation and come to what I believe is a solution (changes in file class-wp-tax-query.php).
Even if the issue is found using Woo product categories I believe this is an issue for taxonomies in general.
Problem:
Using shortcode to retrieve a filtered product list and filtering on two or more product categories using operator “AND” fails when using one or more non-leaf (i.e. parent) product categories. There even seemed to be additional problems when using more than two leaf keywords. In general the ""AND"" didn't behave as expected.
Other reports on the issue:
[https://wordpress.org/support/topic/operator-and-on-product_category/]
[https://wordpress.org/support/topic/woocommerce-display-products-from-two-categories-combined/]
[https://wordpress.org/support/topic/woocommerce-product_category-and-operator-returns-no-results/]
Examples using Woo shortcodes:
Taxonomies (product categories) for Product1: '''Leaf'''CatA, '''Leaf'''CatB
[product_category category=”'''Parent'''CatA, '''Leaf'''CatB” operator=”AND”] => '''Fails''' - shows nothing. Should show Product1
[product_category category=”'''Leaf'''CatA, '''Leaf'''CatB” operator=”AND”] => '''Ok''' - shows Product1
Reason:
There is no individual and complete hierarchial evaluation of each taxonomy/category keyword specified in the shortcode.
Solution that worked for me:
The issue is found in the WP-core file class-wp-tax-query.php. I’ve modified three functions to correct the issue. This includes changes to the SQL-statements generated.
Changes to file class-wp-tax-query.php:
class WP_Tax_Query
- function get_sql_for_clause – code
- function clean_query – input params and code
- function transform_query – input params and code
You find my modified and running code/functions with my comments here (tagged with // BF): [https://gist.github.com/Nettsidespesialisten/5d4596e18dced3c7d97501f195ffe02e]
This is my first ticket here so please notify me how to contribute the best way with this issue (providing code into SVN or other).
Kind regards
Brede
",bredefladen
Tickets Awaiting Review,41446,The PHP notice displayed after the overwriting global $posts by a new empty query.,,Query,4.8,normal,normal,Awaiting Review,defect (bug),new,,2017-07-26T07:57:45Z,2020-08-25T12:46:57Z,"'''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
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
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.",danielpietrasik
Tickets Awaiting Review,58553,Two query blocks on home template (FSE) breaks the second one,,Query,6.2,normal,normal,Awaiting Review,defect (bug),new,,2023-06-16T06:47:30Z,2023-06-16T06:47:30Z,"On a site we have a home.html template where we display a custom query with sticky posts before the main query (inherited). We also filter the main query to do not display sticky posts again. Since we updated to 6.1.3 the second query skips the first post (that is the most recent non-sticky post).
After some debugging I realize that the `$wp_query->current_post` value is 0 after the first loop instead of -1, causing it to skip the first item (index 0) on the `$wp_query->posts array`. Following the logic in wp-includes I cannot find any obvious change introduced on 6.1.3 to produce this error.
I’ve reproduced the issue on a fresh new installation of wp (with 6.2 version):
* I have created several posts (duplications of Hello world)
* I have crated a new category.
* I have assigned three posts to the new category
* I have modified the home template (on the site editor) to add a custom query before the main one, where I display the three posts from the new category
[[Image(https://images2.imgbox.com/3d/5c/wfm9rpvl_o.png)]]
Result with wp 6.1.2
When I update to 6.1.3, the “last one” disapears:
[[Image(https://images2.imgbox.com/43/b0/OMZDY2ba_o.png)]]
I have found a quick fix that solves it:
{{{#!php
is_home){
global $wp_query;
//sets the $wp_query->current_post to -1
$wp_query->current_post = -1;
}
});
}}}
But I assume this may potentially affect more users and should be fixd on the core.
BTW: Using two custom queries doesn’t work for us because we want to keep the default pagination settings with the `/page/2` urls",acaballerog
Tickets Awaiting Review,57412,Uncaught TypeError: Cannot read properties of undefined (reading 'length'): jquery migrate,,Query,6.1.1,normal,critical,Awaiting Review,defect (bug),new,,2023-01-03T01:14:50Z,2023-01-03T01:16:13Z,"Hi everyone!
I've been trying to fix this for days, but no change.
i tried to install different jquery migration plugins, but none solve the error on my site.
probably a plugin needed for the theme to work is in conflict. this plugin is helvig core.
if I go to the web page the problem does not exist, but when I enter the menu and try to go to one of the menu pages it doesn't work and gives me the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at init. (jquery-migrate-3.4.0.min.js?ver=3.4.0:2:8491)
at e. [as run] (jquery-migrate-3.4.0.min.js?ver=3.4.0:2:1566)
at u (jquery-3.6.2.min.js?ver=3.6.2:2:59974)
at E.fx.tick (jquery-3.6.2.min.js?ver=3.6.2:2:65017)
at st (jquery-3.6.2.min.js?ver=3.6.2:2:59376)
(anonymous) @ jquery-migrate-3.4.0.min.js?ver=3.4.0:2
e. @ jquery-migrate-3.4.0.min.js?ver=3.4.0:2
u @ jquery-3.6.2.min.js?ver=3.6.2:2
E.fx.tick @ jquery-3.6.2.min.js?ver=3.6.2:2
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
requestAnimationFrame (async)
st @ jquery-3.6.2.min.js?ver=3.6.2:2
I tried uninstalling themes and plugins. i downloaded the latest version directly on the theme forest purchase page, but no change.
i have tried different plugins to try to use other versions of jquery migrated, but the problem persists.
I also tried downgrading wordpress and completely uninstalled and reinstalled it.
the same problem of the site, I also find it locally.
how can i solve?",russellperez399
Tickets Awaiting Review,58806,Unexpected ordering result when ordering based on multiple clauses,,Query,6.2.2,normal,normal,Awaiting Review,defect (bug),new,,2023-07-14T08:17:52Z,2023-07-14T08:17:52Z,"I am not sure if this is a bug or this is a mis-understanding from my side on how the ordering works but
Consider the following `WP_Query`:
{{{#!php
'ids',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => [
'relation' => 'OR',
'sticky_clause' => [
'key' => '_sticky',
'type' => 'UNSIGNED',
],
[
'key' => '_sticky',
'compare' => 'NOT EXISTS',
],
],
'orderby' => [
'sticky_clause' => 'desc',
'title' => 'asc',
],
]
);
}}}
The expected behavior is that the query should show posts that have a `_sticky` meta first, then shows the rest of the posts sorted by their title alphabetically.
However it doesn't happen.
{{{
array(7) {
[0]=>
string(20) ""A guide to WordPress""
[1]=>
string(27) ""Brotherhood of creativeness""
[2]=>
string(30) ""Gather all information you can""
[3]=>
string(16) ""Yet another post""
[4]=>
string(12) ""Hello world!""
[5]=>
string(36) ""Opera browser released a new version""
[6]=>
string(27) ""Zebras are cool and relaxed""
}
}}}
In the above output of post titles, the `""Hello World!""` has `_sticky` meta, but the sorting isn't correct (nor alphabetically and nor by `_sticky` meta first)
This is the SQL query generated by this query:
{{{#!php
SELECT
wp_posts.ID
FROM
wp_posts
LEFT JOIN wp_postmeta ON (
wp_posts.ID = wp_postmeta.post_id
)
LEFT JOIN wp_postmeta AS mt1 ON (
wp_posts.ID = mt1.post_id
AND mt1.meta_key = '_sticky'
)
WHERE
1 = 1
AND (
wp_postmeta.meta_key = '_sticky'
OR mt1.post_id IS NULL
)
AND wp_posts.post_type = 'post'
AND (
(wp_posts.post_status = 'publish')
)
GROUP BY
wp_posts.ID
ORDER BY
CAST(
wp_postmeta.meta_value AS UNSIGNED
) DESC,
wp_posts.post_title ASC
}}}
If I am not wrong the issue happens at the position `ORDER BY CAST(wp_postmeta.meta_value AS UNSIGNED) DESC`, it should use the alias instead of the table name here (should be `mt1.meta_value`)",pelentak
Tickets Awaiting Review,54268,Using `author_name` in URL parameter gives unexpected results when logged into contributor account,,Query,5.8.1,normal,minor,Awaiting Review,defect (bug),new,,2021-10-14T22:22:48Z,2021-10-14T22:22:48Z,"When logged into a contributor account, and trying to view the post listing on the dashboard of an administrator user, the query changes unexpectedly when the URL uses the `author_name` parameter rather than the default url.
Assuming a user ID of 1 for an administrator user, and a user ID of 2 for a contributor user:
When logged into the contributor account, and displaying the admin user's posts in the dashboard, the URL looks like this and works as expected:
`/wp-admin/edit.php?post_type=post&author=1`
The main query is:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_author IN (1)
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'future'
OR wp_posts.post_status = 'draft'
OR wp_posts.post_status = 'pending'
OR wp_posts.post_author = 2
AND wp_posts.post_status = 'private')
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20
}}}
But if the URL is switched to the username of the administrator user, example, admin, like this `/wp-admin/edit.php?post_type=post&author_name=admin` or even just `/wp-admin/edit.php?author_name=admin` I would expect the same results, but they are different:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_author IN (2)
AND (wp_posts.post_author = 1)
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'future'
OR wp_posts.post_status = 'draft'
OR wp_posts.post_status = 'pending'
OR wp_posts.post_author = 2
AND wp_posts.post_status = 'private')
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20
}}}
The `IN (2)` and the `OR wp_posts.post_author = 2` here is unexpected, because the 2 is the user ID of the contributor user that is logged in, and it isn't relevant to a query for the posts of user ID 1 (admin).
For comparison, when logged into the administrator's account, this query looks like this:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND (wp_posts.post_author = 1)
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'future'
OR wp_posts.post_status = 'draft'
OR wp_posts.post_status = 'pending'
OR wp_posts.post_status = 'private')
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20
}}}
To replicate:
1. Create two users, one with the administrator role, and another with a contributor role.
2. Publish a post for the admin user.
3. While logged into the contributor user's account, view the administrator user's posts in the dashboard. The link will look like `/wp-admin/edit.php?post_type=post&author=1`. Take note of the main query and the search results.
4. Alter the url to look for the username of that administrator user, in this format: `/wp-admin/edit.php?post_type=post&author_name=admin`. Check the main query and search results again.
This appears to be coming from the `get_posts` function in the wp-includes/class-wp-query.php file.
This is a low severity issue that I stumbled upon while investigating a Co Authors Plus [https://github.com/Automattic/Co-Authors-Plus/issues/820 issue], a plugin that uses the `author_name` in the URL. However, even when that plugin is not installed, the above described behavior is replicable.",lschuyler
Tickets Awaiting Review,41546,WP Query order by meta_clause not working correctly for decimal values,,Query,4.2,normal,normal,Awaiting Review,defect (bug),new,,2017-08-03T13:06:36Z,2017-08-05T07:13:01Z,"Short description: When using the WP 4.2 improvements for meta queries (as described here: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/) and trying to order the query by a decimal custom field, wordpress orders as if these fields are all integer and incorrectly handles all decimal values such as 1.5, 1.6 and 1.7 (all of these are seen as 1).
In detail:
{{{
WP_QUERY_ARGS Array
(
[ignore_sticky_posts] => 1
[post_status] => publish
[offset] => 0
[post_type] => Array
(
[0] => post
)
[orderby] => Array
(
[cf_clause_1] => DESC
[ID] => ASC
)
[meta_query] => Array
(
[cf_clause_1] => Array
(
[key] => my_decimal_custom_field
[type] => DECIMAL
[compare] => EXISTS
)
)
[posts_per_page] => 10
[nopaging] =>
)
}}}
5 Test posts:
Post 1 - my_decimal_custom_field = 1
Post 2 - my_decimal_custom_field = 2
Post 3 - my_decimal_custom_field = 2.2
Post 4 - my_decimal_custom_field = 2.6
Post 5 - my_decimal_custom_field = 3
Using the query above results in the order:
1,3,4,2,5
When it should be 1,2,3,4,5.
Trying out different order types as described in the WP Codex does not help.",LordSpackolatius
Tickets Awaiting Review,47009,WP_Query bug with author=0,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2019-04-22T07:10:12Z,2019-04-22T08:17:08Z,"Hi all,
I found a weird behaviour of WP_Query using the argument author.
If author is set to 0, the query returns all the posts and not an empty set.
Is this a wanted behaviour or a bug?",mikylucky
Tickets Awaiting Review,40387,WP_Query bug with product post type with search parameter on,,Query,4.7.3,normal,normal,Awaiting Review,defect (bug),reopened,,2017-04-07T11:07:02Z,2017-04-18T21:09:16Z,"I am not sure if it is a WordPress core bug, but seems like it! I have 5 different custom post types along with 'product' post type from Woocommerce.
The following query gives (only) product result:
{{{
$args = array(
'post_type' => array('product'),
'posts_per_page' => 5,
'post_status' => array('publish', 'future')
);
}}}
Actual query output:
{{{SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'product' AND ((wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future')) ORDER BY wp_posts.post_date DESC LIMIT 0, 5}}}
But the following query:
{{{
$args = array(
'post_type' => array('product'),
's' => 'mobile',
'posts_per_page' => 5,
'post_status' => array('publish', 'future')
);
}}}
outputs this (even post_type is specified the query is generated to search all other post types and surprisingly not product):
{{{SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '%htc%') OR (wp_posts.post_excerpt LIKE '%htc%') OR (wp_posts.post_content LIKE '%htc%'))) AND wp_posts.post_type IN ('post', 'travelog', 'hotel-info', 'trips', 'package_tour') AND ((wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future')) ORDER BY wp_posts.post_title LIKE '%htc%' DESC, wp_posts.post_date DESC LIMIT 0, 5}}}
and brings up results from all other post types and simply ignoring product.
",subrataemfluence
Tickets Awaiting Review,44372,WP_Query cannot properly order by nested Parent/Child relationships,,Query,4.9.6,normal,minor,Awaiting Review,defect (bug),new,,2018-06-14T19:28:48Z,2018-06-14T20:23:58Z,"Steps to reproduce the problem:
- Create a new CPT named `series`.
- Create numerous parent/child relationships in no particular order. Some are nested since we have the concept of seasons and episoded in series. These will not fit properly with taxonomies because data for each ""Season 1"" is unique to the parent series.
- The parent can be added after the child is created and then associated (important as the date is taken into account here as it is unreliable in this case and is a very realistic scenario).
- use `menu_order` as a way to order these items. Seasons `menu_order` will be the season number and episodes are most commonly going to be used 1-10. One could argue season 2 should be 20-30 but that is not normal user expectation when using the system (I already have teams working on this and they all favor 1-10 and not 20... 30... per season. I tried...)
Basically, what you are creating is a bunch of series that have seasons as their immediate children then these seasons have episodes assigned to them. Typical series structure.
Series (parent) -> Season (child of Series, parent of Episode) -> Episode (child of Season).
I can easily filter the results for parents and list the children. The issue I have is that I am not able to sort by children properly.
What I expect is a structure like:
Game of Thrones
{{{
- Season 1
-- Episode 1
-- Episode 2
-- Episode 3
- Season 2
-- Episode 1
-- Episode 2
-- Episode 3
- Season 3
-- Episode 1
-- Episode 2
-- Episode 3
...
}}}
What I get:
Game of Thrones
{{{
- Season 1
- Season 2
- Season 3
-- Episode 1 - season 3
-- Episode 2 - season 3
-- Episode 3 - season 3
-- Episode 1 - season 1
-- Episode 2 - season 1
-- Episode 3 - season 1
-- Episode 1 - season 2
-- Episode 2 - season 2
-- Episode 3 - season 2
...
}}}
I have tried playing with the orderby for all available options and I can not get the structure I expect.
It seems like this is a limitation with the table design as menu_order and post_parent are not enough to create this structure. In fact, you can pretty much only do what I am getting, not what I would expect. It would seem that we need a better way to handle deeper parent/child relationships for this to order properly. Perhaps a meta field would help with this.
I'm not sure if there is anything that can be done here. I am very doubtful. I may have to rethink the system and add more meta fields for ordering as this is going to be a problem for the project.
Reporting this here to see if it's worth anyone's time to research.
I've included my class to help with testing.
{{{
_getAllSeriesParents();
if (empty($_series)) {
return;
}
$selected = isset($_REQUEST[self::REQUEST_SERIES_NAME_VARIABLE]) ? $_REQUEST[self::REQUEST_SERIES_NAME_VARIABLE] : '';
?>
is_main_query()) {
return $query;
}
// Ensure proper post_type and that we have the request var
if ('series' !== $query->query['post_type'] || empty($_REQUEST[self::REQUEST_SERIES_NAME_VARIABLE])) {
// No need to filter, not where we want to be
return $query;
}
// Ok, let's extend the WP_Query to use our filter
// Fetch Series Object so we can extract the season post IDs
$_seriesObject = VideoFactory::getObject($_REQUEST[self::REQUEST_SERIES_NAME_VARIABLE]);
$_seriesSeasons = $_seriesObject->getSeasons();
$_seriesSeasons = array_keys($_seriesSeasons); // gets the season post ID
// build $_parentIDs to be used to limit the result set
$_parentIDs = [(int)$_seriesObject->getPostID()];
$_parentIDs = array_merge($_parentIDs, $_seriesSeasons);
// Modify the query object to use our new filter
$query->query_vars['post_parent__in'] = $_parentIDs;
$query->query_vars['orderby'] = [
'parent' => 'ASC',
'menu_order' => 'ASC'
];
return $query;
}
/**
* Returns all series parents
* @return mixed
*/
private function _getAllSeriesParents() {
if (NULL === $this->allSeriesParents) {
// Build query for genre query
$args = array(
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'post_parent' => 0,
'post_type' => array(
'series'
),
'ignore_sticky_posts' => 1
);
// Do query
$wpQuery = new \WP_Query($args);
if ($wpQuery->have_posts()) {
foreach ($wpQuery->get_posts() as $p) {
// Normal loop logic using $p as a normal WP_Post object
$this->allSeriesParents[$p->ID] = $p->post_title;
}
}
}
return $this->allSeriesParents;
}
}
}}}
Series CPT is:
{{{#!php
array(
'name' => __('Series', 'parables_core'),
'singular_name' => __('Series', 'parables_core'),
'featured_image' => __('Poster Image', 'parables_core'),
'set_featured_image' => __('Set Poster Image', 'parables_core'),
'remove_featured_image' => __('Remove Poster Image', 'parables_core'),
'use_featured_image' => __('Use Poster Image', 'parables_core'),
),
'public' => true,
'menu_position' => 21,
'menu_icon' => 'dashicons-video-alt2',
'hierarchical' => true,
'capability_type' => 'series',
'capabilities' => array(
'edit_post' => ""edit_{$capabilityType}"",
'read_post' => ""read_{$capabilityType}"",
'delete_post' => ""delete_{$capabilityType}"",
'edit_posts' => ""edit_{$capabilityType}s"",
'edit_others_posts' => ""edit_others_{$capabilityType}s"",
'publish_posts' => ""publish_{$capabilityType}s"",
'read_private_posts' => ""read_private_{$capabilityType}s"",
'delete_posts' => ""delete_{$capabilityType}s"",
'delete_private_posts' => ""delete_private_{$capabilityType}s"",
'delete_published_posts' => ""delete_published_{$capabilityType}s"",
'delete_others_posts' => ""delete_others_{$capabilityType}s"",
'edit_private_posts' => ""edit_private_{$capabilityType}s"",
'edit_published_posts' => ""edit_published_{$capabilityType}s""
),
'rewrite' => array(
'with_front' => false
),
'supports' => array(
'title',
'editor',
'page-attributes',
),
)
);
}}}
",son9ne
Tickets Awaiting Review,47802,WP_Query get_posts sometimes inserts contradictory taxonomy queries,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2019-07-30T18:15:54Z,2020-09-04T15:17:24Z,"In our website, we have a custom taxonomy called 'section.' It figures prominently in a query we're doing. Here's a (lightly anonymized) dump of the array we pass to the WP_Query constructor, before calling get_posts() on the query created:
{{{
[posts_per_page] => 25
[post_type] => post
[tax_query] => Array
(
[0] => Array
(
[operator] => IN
[taxonomy] => section
[field] => slug
[terms] => Array
(
[0] => section1
[1] => section2
[2] => section3
[3] => section4
)
)
[1] => Array
(
[operator] => NOT IN
[taxonomy] => section
[field] => slug
[terms] => Array
(
[0] => section5
)
)
[relation] => AND
)
[orderby] => post_date
[order] => DESC
}}}
We had a problem where many posts that should be returned here, are not. After much digging, I found the problem in get_posts. specifically in the segment of code commented:
{{{
/*
* Set 'taxonomy', 'term', and 'term_id' to the
* first taxonomy other than 'post_tag' or 'category'.
*/
}}}
It's true, the code is doing just that. It's adding a taxonomy parameter. But it's picking up one of the sections that is supposed to be one of several possibilities the section can be IN, not required. It then makes that one single section required in an appended AND! Sample (again, lightly anonymized) SQL segment of the obviously self-contradictory conditions created (where 1001-1005 are the IDs corresponding to sections 1-5)
{{{
wp_term_relationships.term_taxonomy_id IN (1001, 1002, 1003, 1004)
AND
wp_posts.ID NOT IN (
SELECT object_id
FROM wp_term_relationships
WHERE term_taxonomy_id IN (1005)
)
AND
tt1.term_taxonomy_id IN (1001)
)
}}}
That third clause, the final IN (1001) is being added by get_posts in the above-commented section. That's why we only get a fraction of the posts we're supposed to get. It's effectively overriding most of our IN list!
I can work around this by prepending to my tax_query an effective no-op using some custom taxonomy, but this seems like a problem that should be addressed in the WP core.
thank you,",nstevensdc
Tickets Awaiting Review,60468,"WP_Query matches any post when query parameter ""name"" is an empty string",,Query,,normal,minor,Awaiting Review,defect (bug),new,,2024-02-07T17:25:07Z,2024-02-07T17:25:07Z,"`WP_Query` matches any post when query parameter `name` is an empty string.
For example:
{{{
$query = new WP_Query([
'name' => '',
'post_type' => 'post',
'posts_per_page' => 1,
]);
var_dump($query->posts);
}}}
The same is true for `get_posts()` which uses `WP_Query` internally.
This might be the intended behavior, but it's unintuitive and surprising. It can (did) cause a bug in user code that expects such a query to return no results.",miyarakira
Tickets Awaiting Review,42546,WP_Query not handling 'LIKE' correctly.,,Query,4.8.3,normal,normal,Awaiting Review,defect (bug),new,,2017-11-14T16:27:03Z,2018-03-14T09:30:49Z,"I am doing custom PHP to retrieve listings (as a CPT) from the database for a Realty Company website I'm working on and one of the criteria is searching on the city from a search field on a form. The problem is the generated SQL has some sort of guid in it instead of the expected percent character normally used with LIKE. Here is the generated SQL from WP_Query:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'city' AND wp_postmeta.meta_value LIKE '{f270e6c7d3b231242ceefa28fdd47243cac2100fe4fe8c9df633ec6f3cc2f583}fairfield{f270e6c7d3b231242ceefa28fdd47243cac2100fe4fe8c9df633ec6f3cc2f583}' ) AND ( mt1.meta_key = 'beds' AND mt1.meta_value >= '0' ) ) AND wp_posts.post_type = 'listings' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
}}}
As you can see the generated code for searching the ""city"" field is:
{{{
wp_postmeta.meta_value LIKE '{f270e6c7d3b231242ceefa28fdd47243cac2100fe4fe8c9df633ec6f3cc2f583}fairfield{f270e6c7d3b231242ceefa28fdd47243cac2100fe4fe8c9df633ec6f3cc2f583}'
}}}
The ""expected"" code should look like this:
{{{
wp_postmeta.meta_value LIKE '%fairfield%'
}}}
The form is found here: https://millersells.com/search-2/
After making selections and clicking the Search button it calls itself with url parameters and you get one of these errors:
""Fatal error: Maximum execution time of 60 seconds exceeded in /home/extremx1/public_html/millersells2017b/wp-includes/query.php on line 0""
OR
""Fatal error: Maximum execution time of 60 seconds exceeded in /home/extremx1/public_html/millersells2017b/wp-includes/class-wp-query.php on line 3090""
(Example URL with parameters: https://millersells.com/search-2/?cf_id=37&loc=fairfield&type=SingleFamilyHome&beds=3&baths=2&min_price=0&max_price=0)
I am using this PHP code to create the query (for now I'm just working with 2 of the search fields):
{{{
array( 'listings' ),
'meta_query' => array(
array(
'key' => 'city',
'value' => $location,
'type' => 'CHAR',
'compare' => 'LIKE',
),
array(
'key' => 'beds',
'value' => $bedrooms,
'compare' => '>='
)
)
);
$the_query = new WP_Query( $args );
?>
}}}
To see the generated SQL I added this code at line 2752 in wp_includes/class-wp-query.php: echo $this->request;
Also to aid in debugging I would suggest you add a ""generated_sql"" parameter to the query object that we can echo to see what the actual generated SQL looks like. EX: {{{echo $the_query->generated_sql;}}}
Thanks!
Tim :o]
PS: Your welcome to contact me at tberneman@gmail.com",tberneman
Tickets Awaiting Review,43634,WP_Query returns wrong result if 10+ search terms and all negative.,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2018-03-26T15:09:42Z,2019-01-17T01:18:05Z,"Set up: create single post with title or body ""Don't match this one!""
Use WP_query with 's' parameter:
{{{
-one -two -three -four -five -six -seven -eight -nine -ten
}}}
WP_Query will find and return the single post and it shouldn't.
Less than 10 negative search terms works fine.
I believe it has to do with a special 'if clause' in the function '''parse_search''' in ''class-wp-query.php''
{{{
// if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 ) {
$q['search_terms'] = array( $q['s'] );
}
}}}
this makes
{{{
JPH q['search_terms'] : Array
(
[0] => -one -two -three -four -five -six -seven -eight -nine -ten
)
}}}
and later in the function the search variable becomes
{{{
JPH search variable is: AND (((testsite_posts.post_title NOT LIKE '{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}one -two -three -four -five -six -seven -eight -nine -ten{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}') AND (testsite_posts.post_excerpt NOT LIKE '{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}one -two -three -four -five -six -seven -eight -nine -ten{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}') AND (testsite_posts.post_content NOT LIKE '{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}one -two -three -four -five -six -seven -eight -nine -ten{07e030b91cb064568b0acafd83d99152667b06f2ffd415e48cd2d2f458c2c217}'))) AND (testsite_posts.post_password = '')
}}}
",johnh10
Tickets Awaiting Review,52971,WP_Query's meta_query With Multiple EXISTS keys and OR Relation Doesn't Work Properly,,Query,5.7,normal,critical,Awaiting Review,defect (bug),new,,2021-04-05T12:31:53Z,2021-04-05T12:31:53Z,"Hi There!
Another Very Weird Issue :)
Using WP_Query's [meta_query] with **OR relation** and Multiple **EXISTS Keys** generates a very long unnecessary inner joins relation and **stuck in an infinite loop** and **consume the MySQL resources** with high load.
I'm trying to get all post IDs that have one of 50 meta keys to replace with new keys, So I collect all meta keys using foreach statement with **OR relation** and pass it to the [meta_query] in WP_Query .. Very simple but I noticed that there's no result and infinite page load and using high resources of MySQL.
I create the SQL statement with $wpdb and it works very fast, So I create a new WP_MetaQuery object to see the result and I noticed a huge unnecessary INNER JOINs relation.
**Here's a full example:**
1. Insert 100 Test Posts and 50 Metas For Each: Append [?action=insert] in the URL
2. Try to get posts using WP_Query: Append [?action=wp_query_and_meta_query] in URL - **RESULT: Infinite Loop**
3. Try to use $wpdb instead: Append [?action=wpdb_query_get_ids] in URL - **RESULT: Success, Takes few seconds**
4. See the SQL statement generated by WP_MetaQuery: add [?action=show_meta_query_clause] - **RESULT: a Huge unnecessary **INNER JOIN x AS x# ON y** relation**
5. [?action=wpdb_query_delete] to delete all added posts only.
{{{
add_action('wp', 'oxibug_trigger_action');
/**
* Trigger Suitable Function
*
* @return void
*/
function oxibug_trigger_action() {
if( ! isset( $_GET['action'] ) ) {
return;
}
$action = wp_strip_all_tags( $_GET['action'] );
switch( strtolower( $action ) ) {
case 'insert': {
oxibug_insert_posts_and_metas();
} break;
case 'wp_query_and_meta_query': {
oxibug_WP_Query_and_meta_query();
} break;
case 'show_meta_query_clause': {
oxibug_show_meta_query_clause();
} break;
case 'wpdb_query_get_ids': {
oxibug_wpdb_query_get_ids();
} break;
case 'wpdb_query_delete': {
oxibug_wpdb_query_delete();
} break;
}
}
/**
* Return New Meta Key
*
* @param mixed $key
* @return string
*/
function oxibug_get_new_meta_key( $key ) {
return sanitize_text_field( sprintf( 'oxibug_xyz%s', $key ) );
}
/**
* Return Key-Value Pairs array with Old and New meta keys
*
* @return array
*/
function oxibug_legacy_and_new_meta_keys() {
return [
'oxibug_abc_post_main_color' => oxibug_get_new_meta_key('_page_main_color'),
'oxibug_abc_page_layout' => oxibug_get_new_meta_key('_page_layout'),
'oxibug_abc_post_sbwide' => oxibug_get_new_meta_key('_page_sb_wide'),
'oxibug_abc_post_sbnarrow' => oxibug_get_new_meta_key('_page_sb_narrow'),
'oxibug_abc_page_sbwide' => oxibug_get_new_meta_key('_page_sb_wide'),
'oxibug_abc_page_sbnarrow' => oxibug_get_new_meta_key('_page_sb_narrow'),
'oxibug_abc_self_video_m4v_url' => oxibug_get_new_meta_key('_format_video_selfhosted_mp4'),
'oxibug_abc_self_video_ogv_url' => oxibug_get_new_meta_key('_format_video_selfhosted_ogv'),
'oxibug_abc_self_video_webmv_url' => oxibug_get_new_meta_key('_format_video_selfhosted_webmv'),
'oxibug_abc_self_video_poster_url' => oxibug_get_new_meta_key('_format_video_selfhosted_poster'),
/* Audio */
'oxibug_abc_soundcloud_url' => oxibug_get_new_meta_key('_format_audio_oembed'),
'oxibug_abc_self_audio_mp3_url' => oxibug_get_new_meta_key('_format_audio_selfhosted_mp3'),
'oxibug_abc_self_audio_oga_url' => oxibug_get_new_meta_key('_format_audio_selfhosted_ogg'),
'oxibug_abc_self_audio_m4a_url' => oxibug_get_new_meta_key('_format_audio_selfhosted_m4a'),
/* Post Formats: Image | Video */
'oxibug_abc_lightbox_check' => oxibug_get_new_meta_key('_format_image_lighbox_enable'),
'oxibug_abc_post_banner_caption' => oxibug_get_new_meta_key('_format_status_banner_caption'),
'oxibug_abc_quote_text' => oxibug_get_new_meta_key('_format_quote_text'),
'oxibug_abc_quote_author' => oxibug_get_new_meta_key('_format_quote_author_name'),
'oxibug_abc_url_text' => oxibug_get_new_meta_key('_format_link_text'),
'oxibug_abc_url_destination' => oxibug_get_new_meta_key('_format_link_url'),
/*
* Layout Settings - if Old = [hide] turn ON the new option
*
* */
'oxibug_abc_post_breadcrumb' => oxibug_get_new_meta_key('_hide_breadcrumb'),
'oxibug_abc_post_meta_info' => oxibug_get_new_meta_key('_hide_metas'),
'oxibug_abc_post_share_box' => oxibug_get_new_meta_key('_hide_share_icons'),
'oxibug_abc_post_tags' => oxibug_get_new_meta_key('_hide_tags_box'),
'oxibug_abc_post_author_box' => oxibug_get_new_meta_key('_hide_author_box'),
'oxibug_abc_related_posts' => oxibug_get_new_meta_key('_hide_related_posts_box'),
'oxibug_abc_posts_navigation' => oxibug_get_new_meta_key('_hide_nav_box'),
/* Review Items */
'oxibug_abc_post_review_types' => oxibug_get_new_meta_key('_review_type'), /* [disabled] => Add 0 to the new meta [_review_show] */
'oxibug_abc_post_review_position' => oxibug_get_new_meta_key('_review_position'),
'oxibug_abc_post_reviews_summation' => oxibug_get_new_meta_key('_review_items_avg'), /* This field is Dynamic - SUM of all review items */
'oxibug_abc_review_item' => oxibug_get_new_meta_key('_review_items'),
'oxibug_abc_post_review_title' => oxibug_get_new_meta_key('_review_title'),
'oxibug_abc_post_review_desc' => oxibug_get_new_meta_key('_review_desc'),
'oxibug_abc_post_review_summary_title' => oxibug_get_new_meta_key('_review_summary_title'),
'oxibug_abc_post_review_summary_desc' => oxibug_get_new_meta_key('_review_summary_desc'),
'oxibug_abc_post_review_user_rates' => oxibug_get_new_meta_key('_review_user_ratings_status'),
'oxibug_abc_post_review_user_rates_bgcolor' => oxibug_get_new_meta_key('_review_user_ratings_result_bgcolor'),
'oxibug_abc_post_review_btn_text' => oxibug_get_new_meta_key('_review_add_btn_text'),
'oxibug_abc_post_review_btn_icon' => oxibug_get_new_meta_key('_review_add_btn_icon'),
'oxibug_abc_post_review_btn_url' => oxibug_get_new_meta_key('_review_add_btn_url'),
'oxibug_abc_post_review_btn_bgcolor' => oxibug_get_new_meta_key('_review_add_btn_bgcolor'),
'oxibug_abc_post_review_pros_word' => oxibug_get_new_meta_key('_review_pros_word'),
'oxibug_abc_post_review_pros_icon' => oxibug_get_new_meta_key('_review_pros_icon'),
'oxibug_abc_post_review_pros_list' => oxibug_get_new_meta_key('_review_pros_list'),
'oxibug_abc_post_review_cons_word' => oxibug_get_new_meta_key('_review_cons_word'),
'oxibug_abc_post_review_cons_icon' => oxibug_get_new_meta_key('_review_cons_icon'),
'oxibug_abc_post_review_cons_list' => oxibug_get_new_meta_key('_review_cons_list'),
/* Post Views */
'oxibug_abc_post_views_count' => oxibug_get_new_meta_key('_post_views'),
];
}
/**
* Insert 100 Test Posts and some Meta Keys
*
*/
function oxibug_insert_posts_and_metas() {
$legacy_and_new_keys = oxibug_legacy_and_new_meta_keys();
$result = [];
for( $i=0; $i<100; $i++ ) {
$post_id = wp_insert_post( [
'post_type' => 'post',
'post_title' => wp_strip_all_tags( sprintf( 'Test Meta Query Post #:%s', $i ) ),
'post_content' => sprintf( 'Test Meta Query Post Content #:%s', $i ),
'post_content_filtered' => '',
'post_excerpt' => '',
'post_status' => 'publish',
// 'post_author' => 1,
// 'post_category' => [],
'comment_status' => '',
'ping_status' => '',
'post_password' => '',
'to_ping' => '',
'pinged' => '',
'post_parent' => 0,
'menu_order' => 0,
'guid' => '',
'import_id' => 0,
'context' => '',
'post_date' => '',
'post_date_gmt' => '',
], TRUE, TRUE );
if( ! is_wp_error( $post_id ) ) {
$result[ $post_id ] = [];
foreach( (array) array_keys( $legacy_and_new_keys ) as $_legacy_key ) {
$upstatus = update_post_meta( $post_id, $_legacy_key, '' );
$result[ $post_id ][ $_legacy_key ] = $upstatus ? 'Added' : 'Failed';
}
/* Clean Cache */
clean_post_cache( $post_id );
}
else {
echo 'ERROR: Insert Post Failed!';
}
}
/* DEBUG */
echo sprintf( '%d Posts Inserted', count( $result ) );
// echo print_r( $result );
}
/**
* --- DEBUG ---
* Show the Meta Query SQL Statement
*
*/
function oxibug_show_meta_query_clause() {
/**
*
* @var wpdb
* */
global $wpdb;
$legacy_meta_keys = oxibug_legacy_and_new_meta_keys();
$meta_query = [
'relation' => 'OR'
];
foreach( (array) array_keys( $legacy_meta_keys ) as $_legacy_key ) {
$meta_query[] = [
'key' => $_legacy_key,
'compare' => 'EXISTS'
];
}
$objMetaQuery = new WP_Meta_Query( $meta_query );
echo print_r( $objMetaQuery->get_sql( 'post', $wpdb->posts, 'ID', NULL ) );
}
/**
* Query using WP_Query and meta_query key inside it
*
*/
function oxibug_WP_Query_and_meta_query() {
/**
*
* @var wpdb
* */
global $wpdb;
$legacy_meta_keys = oxibug_legacy_and_new_meta_keys();
$meta_query = [
'relation' => 'OR'
];
foreach( (array) array_keys( $legacy_meta_keys ) as $_legacy_key ) {
$meta_query[] = [
'key' => $_legacy_key,
'compare' => 'EXISTS'
];
}
$obj_WP_Query = new WP_Query( [
'numberposts' => -1,
'paged' => null,
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => $meta_query,
'fields' => 'ids',
'cache_results' => false,
] );
/*
* Stuck in an Infinite Loop Because of the Huge SQL Statement
* generated by [meta_query]
*
* */
if( $obj_WP_Query->have_posts() ) {
echo sprintf( '%d Posts Found', $obj_WP_Query->found_posts );
/* DEBUG - NOT Working - */
// echo print_r( $obj_WP_Query->meta_query->get_sql( 'post', $wpdb->posts, 'ID', NULL ) );
}
else {
echo 'No Posts Found';
}
$obj_WP_Query->reset_postdata();
wp_cache_flush();
}
/**
* Get Posts IDs by one of the meta_key(s) provided
*
*/
function oxibug_wpdb_query_get_ids() {
global $wpdb;
$legacy_meta_keys = oxibug_legacy_and_new_meta_keys();
$qry = ""SELECT DISTINCT tbl_posts.ID FROM {$wpdb->posts} tbl_posts INNER JOIN {$wpdb->postmeta} tbl_metas ON ( tbl_posts.ID = tbl_metas.post_id ) WHERE"";
/* Add [OR] in the second condition */
$where_clause = 0;
foreach( (array) array_keys( $legacy_meta_keys ) as $_legacy_key ) {
$where_clause++;
$qry .= ( $where_clause === 1 ) ?
$wpdb->prepare( ' tbl_metas.meta_key = %s', esc_sql( $_legacy_key ) ) :
$wpdb->prepare( ' OR tbl_metas.meta_key = %s', esc_sql( $_legacy_key ) );
}
$result = $wpdb->get_results( $qry );
$wpdb->flush();
echo print_r( wp_list_pluck( $result, 'ID' ) );
}
/**
* --- DEBUG ---
*
* DELETE all added Posts by meta_key(s)
*
*/
function oxibug_wpdb_query_delete() {
global $wpdb;
$legacy_meta_keys = oxibug_legacy_and_new_meta_keys();
$qry = ""DELETE tbl_posts, tbl_metas FROM {$wpdb->posts} tbl_posts INNER JOIN {$wpdb->postmeta} tbl_metas ON ( tbl_posts.ID = tbl_metas.post_id ) WHERE"";
$where_clause = 0;
foreach( (array) array_keys( $legacy_meta_keys ) as $_legacy_key ) {
$where_clause++;
$qry .= ( $where_clause === 1 ) ?
$wpdb->prepare( ' tbl_metas.meta_key = %s', esc_sql( $_legacy_key ) ) :
$wpdb->prepare( ' OR tbl_metas.meta_key = %s', esc_sql( $_legacy_key ) );
}
$result = $wpdb->get_results( $qry );
$wpdb->flush();
}
}}}
",oxibug
Tickets Awaiting Review,48029,WP_Query::query only using a single post_status,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2019-09-12T18:27:51Z,2020-05-12T05:01:09Z,"While investigating why `bbp_forum_get_subforums()` was not returning private forums while being a keymaster, I found that WP_Query::query() will only use the first post_status of a given array.
E.g:
{{{
WP_Query Object
(
[query] => Array
(
[post_parent] => 5420
[post_type] => forum
[post_status] => Array
(
[0] => publish
[1] => private
[2] => hidden
)
[posts_per_page] => 50
[orderby] => menu_order title
[order] => ASC
[ignore_sticky_posts] => 1
[no_found_rows] => 1
)
...
[request] => SELECT wpp_posts.ID FROM wpp_posts WHERE 1=1 AND wpp_posts.post_parent = 5420 AND wpp_posts.post_type = 'forum' AND ((wpp_posts.post_status = 'publish')) ORDER BY wpp_posts.menu_order ASC, wpp_posts.post_title ASC LIMIT 0, 50
}}}
The same thing applies if you pass it a comma-separated string of statuses:
{{{
WP_Query Object
(
[query] => Array
(
[post_parent] => 5420
[post_type] => forum
[post_status] => publish,private,hidden
[posts_per_page] => 50
[orderby] => menu_order title
[order] => ASC
[ignore_sticky_posts] => 1
[no_found_rows] => 1
)
...
[request] => SELECT wpp_posts.ID FROM wpp_posts WHERE 1=1 AND wpp_posts.post_parent = 5420 AND wpp_posts.post_type = 'forum' AND ((wpp_posts.post_status = 'publish')) ORDER BY wpp_posts.menu_order ASC, wpp_posts.post_title ASC LIMIT 0, 50
}}}
Steps to replicate (taken from bbpress/includes/forums/template.php):
{{{
$r = bbp_parse_args( $args, array(
'post_parent' => 0,
'post_type' => bbp_get_forum_post_type(),
'post_status' => implode( ',', $post_stati ),
// 'post_status' => $post_stati,
'posts_per_page' => get_option( '_bbp_forums_per_page', 50 ),
'orderby' => 'menu_order title',
'order' => 'ASC',
'ignore_sticky_posts' => true,
'no_found_rows' => true
), 'forum_get_subforums' );
$r['post_parent'] = bbp_get_forum_id( $r['post_parent'] );
// Create a new query for the subforums
$get_posts = new WP_Query();
// No forum passed
$sub_forums = !empty( $r['post_parent'] ) ? $get_posts->query( $r ) : array();
}}}",useStrict
Tickets Awaiting Review,49911,WP_Tax_Query generates incorrect SQL,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2020-04-15T16:25:44Z,2020-04-15T19:33:57Z,"When calling WP_Query($arguments)::get_posts() like:
{{{
$arguments = [
'category__in' = ['7','31','704'],
'post_type' => array('post', 'page'),
'post_status' => array('publish'),
'nopaging' => true
];
}}}
704 is the category for posts and 7, 31 for pages. The following query will be produced:
SELECT bct_posts.* FROM bct_posts LEFT JOIN bct_term_relationships ON (bct_posts.ID = bct_term_relationships.object_id) LEFT JOIN bct_term_relationships AS tt1 ON (bct_posts.ID = tt1.object_id) LEFT JOIN bct_term_relationships AS tt2 ON (bct_posts.ID = tt2.object_id) WHERE 1=1 AND ( bct_term_relationships.term_taxonomy_id IN (704) AND tt1.term_taxonomy_id IN (704) AND tt2.term_taxonomy_id IN (7,31,704) ) AND bct_posts.post_type IN ('post', 'page') AND ((bct_posts.post_status = 'publish')) GROUP BY bct_posts.ID ORDER BY bct_posts.post_date DESC
instead of
SELECT bct_posts.* FROM bct_posts LEFT JOIN bct_term_relationships ON (bct_posts.ID = bct_term_relationships.object_id) WHERE 1=1 AND ( bct_term_relationships.term_taxonomy_id IN (7,31,704) ) AND bct_posts.post_type IN ('post', 'page') AND ((bct_posts.post_status = 'publish')) GROUP BY bct_posts.ID ORDER BY bct_posts.post_date DESC
The first query returns only posts, second one posts, and pages. Please note that categories and tags are enabled for pages.
",janznordman
Tickets Awaiting Review,46347,WP_Term_Query where sql_clauses oddity,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2019-02-26T02:37:08Z,2019-02-26T03:03:52Z,"Hello, I was messing around with a customized version of the WP_Term_Query and noticed something odd.
In the function get_terms, there are a lot of places where {{{$this->sql_clauses['where'][somekey]}}} variables are created.
However, on line [https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-term-query.php#L642 643], this code :
{{{#!php
$where = implode( ' AND ', $this->sql_clauses['where'] );
}}}
only uses the first sub array value found and ignores all the other keys.
Shouldn't this be:
{{{#!php
$where = implode( ' AND ', array_values($this->sql_clauses['where']));
}}}
so that all array elements are included in the where?",vrandom
Tickets Awaiting Review,43391,WP_User_Query bug,,Query,4.9.4,normal,normal,Awaiting Review,defect (bug),new,,2018-02-23T09:47:47Z,2018-03-03T08:44:40Z,"I've got an issue when doing a query with WP_User_Query and trying to list from a specific role AND using 'orderby' => 'post_count'. The query simply fails to list the correct results.
Here are the query arguments:
{{{#!php
array( 'ID', 'user_login', 'display_name' ),
'role' => 'expert',
'number' => $numPosts,
'offset' => $page > 1 ? $numPosts : 0,
'order' => 'DESC',
'orderby' => 'post_count'
);
}}}
If I remove the 'role' argument from the query it works, but with the 'role' included it doesn't.
",zkingdesign
Tickets Awaiting Review,44519,Where are the pages of the headings added with the + add-on (any) ala https://wp-kama.ru/cat/wordpress/codex+xxx,,Query,,normal,normal,Awaiting Review,defect (bug),new,,2018-07-05T10:00:29Z,2018-07-05T14:39:16Z,"Here is the page for this blog (kama) - https://wp-kama.ru/cat/wordpress/codex+xxx
This is a page of the rubric with the added + add-on (any)
She does not give out the content, but her response code is 200 - http://joxi.ru/vAWplvLi13bNqr
It's just that Kama banned the headings for indexing through
meta name = ""robots"" content = ""noindex""
I have the same headings for indexing are allowed.So somehow finding such pages the search drags them to the index.
This is exactly what happens to me and Yandex joyfully informs me that I have dragged another pack of such pages into the index.
How to make sure that an error 404 would appear on the page https://wp-kama.ru/cat/wordpress/codex+xxx
As an option - how to add them
meta name = ""robots"" content = ""noindex""
Thank you.",Dmitriy1973
Tickets Awaiting Review,43445,Wildcard `LIKE` support for `WP_Meta_Query` (and maybe other queries?),,Query,,normal,normal,Awaiting Review,defect (bug),new,,2018-03-01T04:09:44Z,2018-03-02T16:15:22Z,"Passing `LIKE` as the `compare` parameter for a meta query (or `compare_key`, after [42768]) results in what is essentially a ""contains"" query for the literal `value` (or `key`) string. So:
{{{
array(
'compare' => 'LIKE',
'value' => 'foo',
)
}}}
becomes `WHERE ... value LIKE '%foo%'`.
MySQL `LIKE` wildcard characters `%` and `_` are escaped, so it's not possible to do a non-standard anchored search, or any other custom `LIKE` query.
It would be nice if you could pass a string like `foo%` and have the wildcard characters respected.
A few considerations:
1. Syntax. A potential solution is suggested in https://core.trac.wordpress.org/ticket/42409#comment:14. Another possibility is a filter for enabling the ""non-escaped"" version
2. Security. I'm unsure that there's a way to do this without introducing security issues, specifically around the `%` character. Any potential patch would need serious review.",boonebgorges
Tickets Awaiting Review,48768,WordPress 5.3 ajax bug with Elementor 2.7.5,,Query,5.3,normal,critical,Awaiting Review,defect (bug),new,,2019-11-22T15:17:38Z,2019-11-22T15:17:38Z,"To whom it may concern,
I was working on my WordPress site and updated it to the latest version available (5.3), before had the 5.2.4 version, i also updated the plugin Elementors to the latest version 2.7.5 .
I noticed that when i was trying to access their build in option, build query, for the elements, it would give and ajax error of type : **core-query uncaught TypeError: Cannot read property 'ajax' of undefined** .
I tried to downgrade the Elementor to a previous version but it didn't work, than i downgraded the WordPress one version older and it worked normally.
",argentum95
Tickets Awaiting Review,40327,Wrong SQL request for 'EXIST' OR 'NOT EXIST' on same post meta,,Query,4.7,normal,normal,Awaiting Review,defect (bug),new,,2017-03-31T19:57:27Z,2017-03-31T19:57:27Z,"Hi,
I want to make a query on a custom post type (event post type) with custom post status (on air, forthcoming...) joining optional meta (event rating) then order by decreasing rating, defaulting to increasing title.
I'm using 'new WP_Query()' way as secondary loop with the following WP query parameters:
{{{#!php
[
// Valid events only
'post_type' => My_Post_Type::POST_TYPE_EVENT,
'post_status' => [
My_Post_Type::EVENT_STATUS_ON_AIR,
My_Post_Type::EVENT_STATUS_FORTHCOMING,
],
// Join optional rating
'meta_query' => [
'relation'=> 'OR',
[
'key' => My_Post_Type::EVENT_ATTR_RATING,
'compare'=> 'EXISTS',
],
[
'key' => My_Post_Type::EVENT_ATTR_RATING,
'compare' => 'NOT EXISTS',
],
],
// Order by rating then title
'orderby' => [
My_Post_Type::EVENT_ATTR_RATING => 'DESC',
'post_title' => 'ASC',
],
// Limit number
'posts_per_page' => self::NB_HOME_COMING_EVENTS,
]
}}}
Resulting SQL query is:
{{{#!php
SELECT SQL_CALC_FOUND_ROWS cq_posts.* FROM cq_posts
LEFT JOIN cq_postmeta ON ( cq_posts.ID = cq_postmeta.post_id )
LEFT JOIN cq_postmeta AS mt1 ON (cq_posts.ID = mt1.post_id AND mt1.meta_key = 'ev_rating' )
WHERE 1=1 AND (
cq_postmeta.meta_key = 'ev_rating'
OR
mt1.post_id IS NULL
) AND cq_posts.post_type = 'event' AND ((cq_posts.post_status = 'ev_on_air' OR cq_posts.post_status = 'ev_coming'))
GROUP BY cq_posts.ID
ORDER BY cq_postmeta.meta_value+0 DESC, cq_posts.post_title ASC
LIMIT 0, 6
}}}
The result set is not what I was looking for (in fact has no sense at all for me)
The right SQL query should be something like this:
{{{#!php
SELECT SQL_CALC_FOUND_ROWS cq_posts.* FROM cq_posts
LEFT JOIN cq_postmeta ON ( cq_posts.ID = cq_postmeta.post_id AND cq_postmeta.meta_key = 'ev_rating' )
WHERE 1=1 AND cq_posts.post_type = 'event' AND ((cq_posts.post_status = 'ev_on_air' OR cq_posts.post_status = 'ev_coming'))
GROUP BY cq_posts.ID
ORDER BY cq_postmeta.meta_value+0 DESC, cq_posts.post_title ASC
LIMIT 0, 6
}}}
Only one LEFT JOIN is required.
Can anyone confirm it is a bug or tell me what WP query parameters I must use instead ?
Thanks in advance.
",solo14000
Tickets Awaiting Review,48360,`meta_value` is ignored when empty string is provided,,Query,3.2,normal,normal,Awaiting Review,defect (bug),new,,2019-10-17T16:40:23Z,2020-02-13T12:30:59Z,"When trying to create a custom query using `meta_*` parameters, `WP_Meta_Query` will ignore `meta_value` if it is an empty string.
This does appear to be somewhat intentional, since `WP_Query` will set the default value for `meta_value` to an empty string. This can be seen here: https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-meta-query.php#L255
The problem comes when you want to write a query that specifically targets meta keys that have empty values. The `'meta_value' => ''` parameter is stripped, and then the query does not behave properly. Here's an example query:
{{{#!php
'product',
'posts_per_page' => 10,
'meta_key' => '_regular_price',
'meta_value' => '',
'meta_compare' => '=',
);
$query = new WP_Query( $args );
}}}
I would like to propose that an empty string be allowed for `meta_value`. Alternatively, the fact that an empty value will be stripped should at least be documented more clearly so that developers know to expect that behavior.
Props also to @richardbuff for helping identify the issue.",JPry
Tickets Awaiting Review,40300,`title` parameter causes `WP_Query` to return sticky posts.,,Query,4.7.3,normal,normal,Awaiting Review,defect (bug),new,,2017-03-29T14:24:28Z,2017-03-29T14:24:28Z,"When a `title` parameter is present in the WP_Query arguments array then sticky posts are included in the `$query->posts` array.
I'm not sure is it a bug, or is it just an incomplete documentation. The same happens with `post__in` parameter but in this case, I'm sure that it's not a bug because the documentation mentions that sticky posts are returned when using the `post__in` parameter.",wujek_bogdan
Tickets Awaiting Review,45666,"adding ""order"" as query arg to the homepage url you are redirected to the last posts page",,Query,,normal,normal,Awaiting Review,defect (bug),new,,2018-12-16T19:30:08Z,2018-12-18T11:38:25Z,"I've tested it on many sites, with different plugins, no plugins, different themes, default WordPress themes. If you add ?order=something to the home page url you have a redirection to the last posts page.
",giuse
Tickets Awaiting Review,57505,"category archive url ending with ""/0"" should be 404",,Query,,normal,normal,Awaiting Review,defect (bug),new,,2023-01-19T09:33:54Z,2023-05-14T13:17:29Z,"First, if URL is ""/category/cat1/0"", first, it is recognized as `category_name=""cat1/0""`,
then ""is_category=true"" and category archive template should be selected.
But for really query, `category_name=""0""` and `empty($q[""category_name""])==true`,
so it is recognized as ""category is not specified"", then `tax_query` will be empty, and `queried_object==null`.
Finally, category template will be confused.
No category is selected, any category related information are broken (maybe rise warnings or errors).
Any recent posts of any public post types will be displayed even if its post_type dose not belong to core 'category' taxonomy.",obache
Tickets Awaiting Review,57766,filter query_loop_block_query_vars repeater 4 times,,Query,6.1.1,normal,normal,Awaiting Review,defect (bug),new,,2023-02-18T21:20:51Z,2023-02-18T21:40:51Z,"Hello! I think that filter query_loop_block_query_vars be repeated 4 times foreach query.
Tried to use this simple code in functions.php(theme Twenty Twenty-Two, no plugins):
add_filter( 'query_loop_block_query_vars', function( $query, $block ){
echo '1 ';
return $query;
}, 21, 2 );
You can notice 4 times 1 on top of the page.",gigito78
Tickets Awaiting Review,53495,incorrect (and confusing) DocBlock for get_page_by_title(),,Query,5.3,normal,normal,Awaiting Review,defect (bug),new,,2021-06-24T00:41:14Z,2021-06-24T00:42:10Z,"The DocBlock of [https://developer.wordpress.org/reference/functions/get_page_by_title/ get_page_by_title()] says:
> If more than one post uses the same title, the post with the smallest ID will be returned. Be careful: in case of more than one post having the same title, it will check the oldest publication date, not the smallest ID.
That description was added in [45779].
Besides the fact that the text after `Be careful:` seems to contradict that the statement that `the post with the smallest ID will be returned`, there actually is no guarentee that if there is more than 1 post with the same title that the one with the smallest ID will be returned.
The query performed by [https://core.trac.wordpress.org/browser/trunk/src/wp-includes/post.php#L5534 get_page_by_title()] is:
{{{#!php
$sql = $wpdb->prepare(
""
SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type = %s
"",
$page_title,
$post_type
);
}}}
(with a slight mod if an array of post types is passed).
Since there is no `ORDER BY` clause in that query, if there are more than 1 posts with the same title the order in which they are returned is not defined by SQL (i.e., is implemented dependent).
The SQL-92 spec [http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt explicitly states]:
> General Rules
>
> 1) All General Rules of Subclause 7.10, """", apply
> to the .
>
> 2) Let Q be the result of the .
>
> 3) If Q is empty, then a completion condition is raised: no data.
>
> 4) If an is not specified, then the ordering of
> the rows of Q is implementation-dependent.
As far as I can tell, no later revisions of the SQL spec are available for free on the web, so I don't know if anything has changed in the what the language says happens in the absense of an `ORDER BY` clause
I've looked through the MySQL and Maria DB docs for an explicit statement that says as much and haven't been able to find one.
But I think the DocBlock should be changed to say something like:
> If more than one post uses the same title, which of the multiple posts is returned is not defined.
though I'm not completely happy with that wording, and welcome other suggestions.
",pbiron
Tickets Awaiting Review,49550,"is_home is set to true even for cron jobs, which causes sticky posts to get prepended to all WP_Query results",,Query,5.3.2,normal,normal,Awaiting Review,defect (bug),new,,2020-02-28T21:10:32Z,2023-02-24T23:41:36Z,"Hi,
We just ran into a bug where sticky posts were prepended to the list of posts being processed by a WP cron job in a new `WP_Query` like this:
{{{
$query = new WP_Query([
'post_status' => 'future',
'date_query' => array(
'before' => '- 1 minute'
),
'numberposts' => -1
]);
}}}
To my surprise, once someone stickied a post, our function in the cron job started doing stuff to the stickied posts, even though it simply runs in WP cron and we're not on the homepage.
I then looked at the logic that determines if the sticky posts get prepended.
{{{
// Put sticky posts at the top of the posts array
$sticky_posts = get_option( 'sticky_posts' );
if ( $this->is_home && $page <= 1 && is_array( $sticky_posts ) && ! empty( $sticky_posts ) && ! $q['ignore_sticky_posts'] ) {
}}}
So this can only fire when `is_home` is true. But how can it be? We're running via WP cron.
Looking at that logic:
{{{
if ( ! ( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots ) ) {
$this->is_home = true;
}
}}}
Since none of these are set - we're in WP cron - `is_home` gets set to true. That doesn't seem right. Is this a sneaky bug or am I missing something? Shouldn't it also check if it's running in cron here and not set `is_home` if so?",archon810
Tickets Awaiting Review,45400,last of query_vars contains anchor,,Query,4.9.8,normal,normal,Awaiting Review,defect (bug),new,,2018-11-22T16:23:44Z,2018-12-05T17:17:29Z,"Anchor links (at least individual comment links) are generated basically by appending ""/#Comment-XX"" to the end of URL.
In which case $wp_query->$query_vars returns last variable with appended ""/"" in it.
",visnevskis
Tickets Awaiting Review,48280,orderby meta_value breaks with newer versions of MySQL,,Query,5.2.3,normal,normal,Awaiting Review,defect (bug),new,,2019-10-10T19:01:27Z,2020-01-30T23:03:53Z,"When running a query like this:
{{{#!php
'course_record',
'posts_per_page' => -1,
'orderby' => 'meta_value',
'meta_key' => 'start_date'
));
?>
}}}
which results in the following SQL query:
{{{#!sql
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_postmeta.meta_key = 'start_date' ) AND wp_posts.post_type = 'course_record' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC
}}}
On MySQL v5.7.25, it works fine and returns posts as expected.
On MySQL v8.0.16, it returns zero posts without any errors.
The weird thing is, if I try to run the SQL statement from above directly into the MySQL console '''on either MySQL version''', I get the following error:
{{{#!text
ERROR 1055 (42000): Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'wp_artofed.wp_postmeta.meta_value' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
}}}
I also get the same error if I try the SQL statement directly in PHP outside of WordPress '''again, on either MySQL version''':
{{{#!php
connect_error) die(""Connection failed: $conn->connect_error"");
if (!$results = $conn->query(""SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_postmeta.meta_key = 'start_date' ) AND wp_posts.post_type = 'course_record' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC"")) {
die(""Query Error: $conn->error"");
}
?>
}}}
However it works if I use `$wpdb->get_results` '''on MySQL v5.7.25''' but not v8.0.16:
{{{#!php
get_results(""SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_postmeta.meta_key = 'start_date' ) AND wp_posts.post_type = 'course_record' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC"");
?>
}}}
I was able to get everything working however by adding `wp_postmeta.meta_value` to the `GROUP BY` clause:
{{{#!php
query_vars) &&
$query->query_vars['orderby'] === 'meta_value'
) {
global $wpdb;
$groupby .= "", {$wpdb->postmeta}.meta_value"";
}
return $groupby;
}
?>
}}}",KodieGrantham
Tickets Awaiting Review,40166,query_vars bug sets is_home to false.,,Query,4.7.3,normal,normal,Awaiting Review,defect (bug),new,,2017-03-15T18:36:27Z,2019-05-20T09:17:12Z,"Hi @boonebgorges, in reference to an older ticket - #25143 following is the issue i am facing.
Similar to the other ticket, when registering a query variable as follows:
{{{#!php
query_vars;
$args = [
'meta_key' => 'my_meta_key',
'orderby' => 'meta_value',
'order' => 'ASC',
];
$query->query_vars = array_merge($queryVars, $args);
});
}}}
And for `pre_get_posts` this technique would work. But with `pre_get_terms` it's different. Digging into `WP_Term_Query` class code I found that this code would cause `parse_orderby()` method to set the `$maybe_orderby_meta` variable to `true`. But it doesn't mean that terms will be sorted by a meta field. It only means that terms '''maybe''' will be sorted by meta.
There's an another filter required. At the end of the `parse_orderby()` method there's an another filter applied: `get_terms_orderby`.
So in order to sort terms by meta field there's one more thing required. Something like:
{{{#!php
true ) );
$status_clauses = array();
foreach ( $public_statuses as $public_status ) {
$status_clauses[] = ""{$wpdb->posts}.post_status = '$public_status'"";
}
...
}}}
This code does not allow to filter statuses depending on other query vars, since neither get_post_stati or wp_filter_object_list (used by get_post_stati) have any hookable filter.
User scenario : I need to filter shop_order posts by a custom taxonomy.
I need to be able to select shop_order without any assigned term from this taxonomy, but only if they're ""live"" ( processing, completed, etc. but not refunded, failed or cancelled), as I don't care if a cancelled Order has no assigned term from this taxonomy.
So if
{{{
$WP_Query->query_vars['post_type'] == 'shop_order'
&& $_GET['taxonomy'] == -1
}}}
( -1 being the value I put in the admin select field to select orders without relationship to the taxonomy )
I want to be able to filter $public_statuses = get_post_stati( array( 'public' => true ) ); to remove 'dead' statuses from the list
current where clause =
AND wp_posts.post_type = 'shop_order' AND ((wp_posts.post_status = 'wc-pending' OR wp_posts.post_status = 'wc-processing' OR wp_posts.post_status = 'wc-on-hold' OR wp_posts.post_status = 'wc-completed' OR wp_posts.post_status = 'wc-cancelled' OR wp_posts.post_status = 'wc-refunded' OR wp_posts.post_status = 'wc-failed' OR wp_posts.post_status = 'wc-partially-paid'))
expected where clause =
AND wp_posts.post_type = 'shop_order' AND ((wp_posts.post_status = 'wc-pending' OR wp_posts.post_status = 'wc-processing' OR wp_posts.post_status = 'wc-on-hold' OR wp_posts.post_status = 'wc-completed' OR wp_posts.post_status = 'wc-partially-paid'))
My own hook hooks on 'posts_where' and add the filter
{{{#!php
prepare(
"" AND ID IN (
SELECT object_id
FROM "". $wpdb->term_relationships . ""
WHERE term_taxonomy_id = %d
)
"", $term_taxonomy_id
);
}}}
and since I'm filtering the $where string of the SQL query, I _could_ remove the 'dead' statuses by str_replace on the where clause, but that's really ugly
I propose this code
{{{#!php
[
'year' => date( 'Y', $date ),
'month' => date( 'm', $date ),
'day' => date( 'd', $date ),
'hour' => date( 'H', $date ),
'minute' => date( 'i', $date ),
'second' => date( 's', $date ),
],
] );
}}}
There is no argument on WP_Date_Query that accepts a `strtotime()`-compatible string for an exact date match. One workaround is to use a combination of before/after to get a simplified query.
Adding support for an exact match can be used when querying for posts from a specific date as well as including/excluding posts from a specific date for a complex query. Suggested syntax:
{{{
// Query for posts after January 1st, 2013 OR exactly on November 7th, 2010
[
'date_query' => [
'relation' => 'OR',
[
'after' => 'January 1st, 2013',
],
[
'exact' => 'November 7th, 2010',
],
],
]
}}}
Relates to #18694.",sean212
Tickets Awaiting Review,47694,Adding a filter for $searchand variable,,Query,,normal,normal,Awaiting Review,enhancement,new,,2019-07-13T11:38:03Z,2019-07-13T11:55:05Z,"Hi,
I wish to know if we can add a filter to the $searchand variable in parse_search method to give the developer the option to modify the logic to OR instead of AND. I believe it will help a lot as it happens in some websites where people search for many words will not be accurate. In these cases OR may be better.",bebro
Tickets Awaiting Review,51155,Default Order and Order By for Post Types and Taxonomies,,Query,,normal,normal,Awaiting Review,enhancement,new,,2020-08-27T04:27:23Z,2020-08-27T12:09:36Z,"Inspired by #49912.
When you register a custom post type, or a taxonomy, you should be able to set the default order(ASC or DESC) and order by parameter for that post type or taxonomy archive.
",dshanske
Tickets Awaiting Review,40341,Make search possible in custom fields,,Query,4.8,normal,normal,Awaiting Review,enhancement,new,,2017-04-02T17:36:06Z,2017-04-02T17:36:06Z,"Currently when performing a search query with `WP_Query` using `s` parameter, WordPress only searches in post_title, post_content and post_excerpt. I suggest to extend search to custom fields.
Say I added a ""my_description"" custom post field to my posts. I would like a regular search to return every post containing the searched word(s) in any of the fields post_title, post_content, post_excerpt or my_description.
Currently the supposed way of doing this is by using a `WP_Meta_Query`:
{{{
new WP_Query(array(
's' => 'foo',
'meta_query' => array(array(
'key' => 'my_description',
'value' => 'foo',
'compare' => 'LIKE',
)),
))
}}}
The problem is that the meta query and the search WHERE clauses are going to be joined by AND, not by OR. The resulting query is going to be something like that:
{{{
SELECT [...] WHERE
(
posts.post_title LIKE '%foo%'
OR posts.post_content LIKE '%foo%'
OR posts.post_excerpt LIKE '%foo%'
) AND (
postmeta.meta_key = 'my_description' AND postmeta.meta_value LIKE '%foo%'
) AND [...]
}}}
But I'd need:
{{{
SELECT [...] WHERE
(
posts.post_title LIKE '%foo%'
OR posts.post_content LIKE '%foo%'
OR posts.post_excerpt LIKE '%foo%'
OR (postmeta.meta_key = 'my_description' AND postmeta.meta_value LIKE '%foo%')
) AND [...]
}}}
which is impossible to achieve with a regular `WP_Meta_Query`. Actually it's pretty hard to do: it involves to hook into WHERE and JOIN clauses, and to rewrite almost the whole search mechanism.
That's why I suggest to implement into core a simple way of doing this:
{{{
new WP_Query(array(
's' => 'foo',
'meta_search' => array('my_description', 'my_other_field', 'etc')
))
}}}
This `meta_search` parameter would accept an array of meta_key strings and would just be ignored when not set.
Please have a look into my attached solution.",max345
Tickets Awaiting Review,42907,Meta Queries: support ordering by meta_value but still including items without that key,,Query,,normal,normal,Awaiting Review,enhancement,new,,2017-12-14T21:54:48Z,2019-01-16T06:50:09Z,"Consider this scenario:
- You want to order a query's results by `meta_value` of a particular `meta_key`.
- Not all items have that key/value pair set.
- You want to still include those items in the results.
- You want them to be ordered as if the `meta_value` is `NULL` (or `0` if using `meta_value_num`).
There is currently no way to do this. (But it is a desired feature, see [https://wordpress.stackexchange.com/questions/28409/way-to-include-posts-both-with-without-certain-meta-key-in-args-for-wp-query 1] [https://wordpress.stackexchange.com/questions/102447/sort-on-meta-value-but-include-posts-that-dont-have-one?noredirect=1&lq=1 2] [https://stackoverflow.com/questions/17016770/wordpress-order-by-meta-value-if-it-exists-else-date 3].)
If you don't care about the items that don't have the meta key set being included, then you can use `compare` => `EXISTS`.
{{{#!php
'meta_value',
'meta_query' => array(
array(
'key' => 'test',
'compare' => 'EXISTS',
),
),
)
);
}}}
However, that won't work if we want to include results where the key/value pair doesn't exist.
A workaround is to do something like this:
{{{#!php
'meta_value',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'test',
'compare' => 'EXISTS',
),
array(
'key' => 'test',
'compare' => 'NOT EXISTS',
),
),
)
);
}}}
This approach solves the problem of the items with no key/value pair not being included. However, it does not order those items in the results reliably. Instead of the `meta_value` being interpreted as `null` (which we might expect), the database will choose another `meta_value` entry for that item to order that item based on.
My proposal is to add a `NONE` option for `compare`, so that it would be possible to achieve the desired ordering with a query like this:
{{{#!php
'meta_value',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'test',
'compare' => 'NONE',
),
),
)
);
}}}
This would result in a query that included a `LEFT JOIN` on the meta table for that `meta_key`, but did not include any conditions in the query. (This is basically a `NOT EXISTS` query but without the `ID = NULL` requirement, so that it is just a left join and not a left outer join.)
When using `meta_value_num` in particular though, ordering by `NULL` may not be desirable (those results will be after all other results); `0` may be preferred as the imputed value (consider a case when negative values are present). To make this possible, I suggest allowing the clause to also specify a `default` value, which will be used in the `ORDER BY` clause with `COALESCE`.
Initial patch forthcoming.",jdgrimes
Tickets Awaiting Review,41843,Provide more flexibility to the `get_{$adjacent}_post_where` hook,,Query,4.9,normal,normal,Awaiting Review,enhancement,new,,2017-09-09T15:33:07Z,2019-03-13T18:09:55Z,"I'm working on getting the previous/next post for a Custom Post Type based on a certain postmeta value, and the `get_{$adjacent}_post_where` seems the appropriate hook for this. However, it currently receives the whole WHERE clause as a parameter. IMO it would be ideal to be able to override just the `WHERE p.post_date $op %s AND p.post_type = %s` part and keep the other (useful ones) intact.
This could potentially be solved in a non-breaking way by sending `$where` as it stands ''before'' concatenation with `WHERE p.post_date $op %s AND p.post_type = %s`, so that authors can neatly plugin a postmeta condition.",danburzo
Tickets Awaiting Review,39708,Provide suppress_actions argument on WP_Query::get_posts or apply suppress_filters to pre_get_posts,,Query,4.7.1,normal,normal,Awaiting Review,enhancement,new,,2017-01-26T18:03:33Z,2018-07-03T16:12:19Z,"{{{#!php
parse_query();
/**
* Fires after the query variable object is created, but before the actual query is run.
*
* Note: If using conditional tags, use the method versions within the passed instance
* (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
* like is_main_query() test against the global $wp_query instance, not the passed one.
*
* @since 2.0.0
*
* @param WP_Query &$this The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'pre_get_posts', array( &$this ) );
// Shorthand.
$q = &$this->query_vars;
}}}
I'm proposing that, just like we have `$q['suppress_filters']` that we add a `$q['suppress_actions']` to prevent actions like `pre_get_posts` from running (which is essentially a filter) on my query (if I want).
We could also apply `$q['suppress_filters']` to the `pre_get_posts` action since the user can modify the query since it's passed by reference, and may not create another argument, but it is not really a filter.
I'm not sure how this idea could be problematic, nor can I think of any reason why we couldn't do anything like this, but I thought I'd at least open it up for discussion and see what becomes of it. I guess my question really is why can I suppress filters but not actions?",aubreypwd
Tickets Awaiting Review,52386,Should WP_Query::get_posts be a private method?,,Query,,normal,normal,Awaiting Review,enhancement,new,,2021-01-27T21:57:25Z,2021-01-27T22:00:00Z,"Sometimes, users call `WP_Query::get_posts()` incorrectly, as it is a publicly accessible method:
{{{#!php
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
posts;
}}}
...Or in the case where no arguments are directly passed into a new WP_Query:
{{{#!php
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!",rebasaurus
Tickets Awaiting Review,58593,Slow list of posts in the admin panel (with a large wp_posts table),,Query,6.2.2,normal,normal,Awaiting Review,enhancement,new,,2023-06-21T17:23:18Z,2023-06-26T15:42:55Z,"Hello. With a large wp_posts table (more than 1 GB, more than 100k published posts), the list of posts in the admin panel may open for several seconds. Slow SQL query that calculates the number of ""my"" posts:
SELECT COUNT( 1 )
FROM wp_posts
WHERE post_type = ''
AND post_status NOT IN ( 'trash','auto-draft','inherit','request-pending','request-confirmed','request-failed','request-completed' )
AND post_author = 1
Solution:
ALTER TABLE `wp_posts`
ADD KEY `type_status_author` (
`post_type`,
`post_status`,
`post_author`
);",Shoorf
Tickets Awaiting Review,40404,Slow queries with a large number of posts (tens of thousands and above),,Query,4.7.3,normal,normal,Awaiting Review,enhancement,new,,2017-04-10T19:23:04Z,2017-04-10T19:28:25Z,"translation yandex:
TASK:
Faced with such a problem that when the number of posts of 20 000+, the sample was held for 30 seconds each page. That is, the database constantly selects all records to select all of a certain number (items per page). The computer is weak for the global scale, but plans to increase to 7 000 000+ posts. Usually hard disks are not the problem.
QUESTION: is There a possibility to optimize the sample?
My SOLUTION (working in project MySQL): (maybe I should add this decision to the release of WP)
Therefore, the solution is selected such that, upon receipt of a sample using the function get_posts () (wp-includes/class-wp-query.php) you need to ""intercept"" a standard request, modify the request function and give the already constructed list.
To store ""lists"" of sorting in the database was created table:
###
CREATE TABLE `wp_сорт` (
`номер_сорта` int(10) unsigned NOT NULL AUTO_INCREMENT,
`значение_сорта` text NOT NULL,
`время_сорта` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`период_сорта` int(10) unsigned NOT NULL,
`мд5_сорта` varchar(32) NOT NULL,
`записей_сорта` int(10) unsigned NOT NULL,
`вызов_сорта` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
PRIMARY KEY (`номер_сорта`),
UNIQUE KEY `инд_мд5_сорта` (`мд5_сорта`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `wp_сортировка` (
`номер_поста` bigint(20) unsigned NOT NULL,
`номер_страница` int(10) unsigned NOT NULL DEFAULT '0',
`номер_на_странице` tinyint(3) unsigned NOT NULL DEFAULT '0',
`номер_сорта` int(10) unsigned NOT NULL DEFAULT '1',
UNIQUE KEY `уник` (`номер_страница`,`номер_на_странице`,`номер_сорта`) USING BTREE,
KEY `внешка_поста` (`номер_поста`) USING BTREE,
KEY `внешка_сорта` (`номер_сорта`),
CONSTRAINT `внешка_поста` FOREIGN KEY (`номер_поста`) REFERENCES `wp_posts` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `внешка_сорта` FOREIGN KEY (`номер_сорта`) REFERENCES `wp_сорт` (`номер_сорта`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
###
Modification of the file wp-includes/class-wp-query.php in the function get_posts () somewhere 2513 string to find:
###
{{{#!php
0 && !isset( $q[ 'search_terms' ] );
if ( $bMod ) {
$мЗначение = [
""join"" => $join,
""where"" => $where,
""groupby"" => $groupby,
""orderby"" => $orderby,
""posts_per_page"" => $q[ ""posts_per_page"" ]
];
$сЗначение = serialize ( $мЗначение );
$сМд5 = md5 ( $сЗначение );
$aR = $wpdb->get_results ( ""SELECT `номер_сорта`, `записей_сорта` FROM `wp_сорт`
WHERE
`мд5_сорта`='{$сМд5}'"", ARRAY_A );
$sTime = date ( ""Y-m-d H:i:s"", strtotime ( ""now"" ) + 14400 );
if ( !$aR ) {
$stable = ""wp_сорт"";
$sColumName = ""номер_сорта"";
$iN = $wpdb->get_var ( 'SELECT t1.' . $sColumName . '+1
FROM ' . $stable . ' AS t1
LEFT JOIN ' . $stable . ' AS t2
ON t1.' . $sColumName . '+1 = t2.' . $sColumName . '
WHERE t2.' . $sColumName . ' IS NULL
ORDER BY t1.' . $sColumName . '
LIMIT 1' );
$wpdb->insert (
""wp_сорт"",
[
""номер_сорта"" => $iN,
""значение_сорта"" => $сЗначение,
""период_сорта"" => 86400,
""мд5_сорта"" => $сМд5,
""вызов_сорта"" => $sTime
],
[
'%d',
'%s',
'%d',
'%s',
'%s'
]
);
$чНомерСорта = $wpdb->insert_id;
$iPerPage = $q[ ""posts_per_page"" ] - 1;
$iQ = $wpdb->query (
""SET @iVar = -1;"" );
$iQ = $wpdb->query (
""SET @iVar2 = 0;"" );
$sQ = ""INSERT INTO `wp_сортировка`
SELECT SQL_CALC_FOUND_ROWS @iVar3:=wp_posts.ID,
IF(@iVar={$iPerPage},@iVar2:=@iVar2+1,IF(ISNULL(@iVar2), @iVar2:=0 , @iVar2)) t,
IF(@iVar<"" . $iPerPage . "",@iVar:=@iVar+1,@iVar:=0) t1,
{$чНомерСорта}
FROM wp_posts {$join}
WHERE 1=1 {$where} {$groupby} {$orderby}
ON DUPLICATE KEY UPDATE `номер_поста`=@iVar3;"";
$wpdb->query ( $sQ );
$q[ ""iRows"" ] = $iRows = $wpdb->get_var ( ""SELECT FOUND_ROWS()"" );
$wpdb->update ( ""wp_сорт"", [
""записей_сорта"" => $iRows, ""время_сорта"" => $sTime
],
[ ""номер_сорта"" => $чНомерСорта ] );
} else {
$чНомерСорта = $aR[ 0 ][ ""номер_сорта"" ];
$wpdb->update ( ""wp_сорт"", [ ""вызов_сорта"" => $sTime ],
[ ""номер_сорта"" => $чНомерСорта ] );
$q[ ""iRows"" ] = $iRows = $aR [ 0 ][ ""записей_сорта"" ];
}
if ( isset ( $q[ ""paged"" ] ) && $q[ ""paged"" ] )
$iPaged = $q[ ""paged"" ] - 1;
else
$iPaged = 0;
$this->request = ""SELECT $found_rows $distinct {$wpdb->posts}.ID FROM
{$wpdb->posts} $join WHERE
{$wpdb->posts}.ID IN(SELECT `номер_поста` FROM `wp_сортировка` WHERE `номер_страница`={$iPaged}
AND `номер_сорта`={$чНомерСорта}) GROUP BY {$wpdb->posts}.ID"";
//echo 0;
} else {
$this->request = ""SELECT $found_rows $distinct {$wpdb->posts}.ID FROM {$wpdb->posts} $join WHERE
1=1 $where $groupby $orderby $limits"";
}
}}}
###
To give the number of records in set_found_posts function ( $q, $limits ) change:
###
{{{#!php
found_posts = $wpdb->get_var ( apply_filters_ref_array ( 'found_posts_query', [ 'SELECT FOUND_ROWS()', &$this ] ) );
}}}
###
on:
###
{{{#!php
found_posts = $q[ ""iRows"" ];
else
$this->found_posts = $wpdb->get_var ( apply_filters_ref_array ( 'found_posts_query', [ 'SELECT FOUND_ROWS()', &$this ] ) );
}}}
###
in cron you need to add one-time during installation, for example, the plugin task:
###
{{{#!php
xray_sorting';
$aR = $wpdb->get_results ( ""SELECT * FROM `wp_сорт` WHERE (NOW()>DATE_ADD(`время_сорта`,INTERVAL `период_сорта`
SECOND) OR `время_сорта`<`вызов_сорта`) AND `номер_сорта`>0"", ARRAY_A );
foreach ( $aR as $aV ) {
$aЗначение = unserialize ( $aV[ ""значение_сорта"" ] );
$iPerPage = $aЗначение[ ""posts_per_page"" ] - 1;
$iQ = $wpdb->query (
""SET @iVar = -1;"" );
$iQ = $wpdb->query (
""SET @iVar2 = 0;"" );
$sQ = ""INSERT LOW_PRIORITY INTO `wp_сортировка`
SELECT SQL_CALC_FOUND_ROWS @iVar3:=wp_posts.ID,
IF(@iVar={$iPerPage},@iVar2:=@iVar2+1,IF(ISNULL(@iVar2), @iVar2:=0 , @iVar2)) t,
IF(@iVar<"" . $iPerPage . "",@iVar:=@iVar+1,@iVar:=0) t1,
{$aV[""номер_сорта""]}
FROM wp_posts {$aЗначение[""join""]}
WHERE 1=1 {$aЗначение[""where""]} {$aЗначение[""groupby""]} {$aЗначение[""orderby""]}
ON DUPLICATE KEY UPDATE `номер_поста`=@iVar3;"";
$iQ = $wpdb->query ( $sQ );
if ( !$wpdb->last_error == """" ) {
echo ""\nсорт {$iQ} "" . $aV[ ""номер_сорта"" ] . "": провал: "" . htmlspecialchars ( $sQ ) . "" "" . $wpdb->last_error
. "";"";
} else {
echo ""\nсорт {$iQ} "" . $aV[ ""номер_сорта"" ] . "": норма;"";
}
$iRows = $wpdb->get_var ( ""SELECT FOUND_ROWS()"" );
echo $wpdb->update ( ""wp_сорт"", [
""записей_сорта"" => $iRows, ""время_сорта"" => date ( ""Y-m-d H:i:s"", strtotime
( ""now"" ) + 14400 )
],
[
""номер_сорта"" => $aV[ ""номер_сорта"" ]
] );
}
# Стираем старые записи сортировок 604800 сек - это 7 суток
$wpdb->query ( ""DELETE FROM `wp_сорт` WHERE `вызов_сорта`<"" . date ( ""Y-m-d H:i:s"", strtotime ( ""now"" ) - 604800 ) . "" AND `номер_сорта`>0"" );
}
}}}
###
I repeat that this is a working model. Can requires file. But all the errors which may be in code(commas, spaces, something like that) is the problem of copy-paste.
[https://ru.wordpress.org/support/topic/%d0%bc%d0%b5%d0%b4%d0%bb%d0%b5%d0%bd%d0%bd%d0%b0%d1%8f-%d1%80%d0%b0%d0%b1%d0%be%d1%82%d1%8b-%d0%b2%d1%8b%d0%b1%d0%be%d1%80%d0%ba%d0%b8-%d0%bf%d1%80%d0%b8-%d0%b1%d0%be%d0%bb%d1%8c%d1%88%d0%be%d0%bc/]",xrayboy
Tickets Awaiting Review,49296,Split up WP_Query into more manageable classes,,Query,5.3.2,normal,normal,Awaiting Review,enhancement,new,,2020-01-26T15:04:24Z,2020-01-26T22:16:29Z,"as it stands the WP_query class file is over 4000 lines
and with a single function that get_posts that on its own is over 1200 lines.
Suggestion
-------------------------------------------------------------------------
Split the class into its own folder with
""vars"",""get"",""set"",""deprecated"",""process"",""comments"",""posts"",""get_posts""
as abstract classes
example
{{{#!php
}}}
and then adjust the class-wp-query.php to load the split class
{{{#!php
query( $query );
}
}
}
}}
after this is done other improvements should be made to the get_posts function.",madpeter
Tickets Awaiting Review,42082,Support compare custom fields in WP_Meta_Query,,Query,4.9.4,normal,normal,Awaiting Review,enhancement,new,,2017-10-04T01:30:51Z,2018-02-28T13:32:39Z,"The syntax of `WP_Meta_Query` currently is limited to values you already know.
It's not possible to compare between two meta_values:
{{{
SELECT posts WHERE meta_value_one > meta_value_two
}}}
I propose allow compare two meta_fields. For example, the pseudocode above would be represented as a meta_query argument that looks like this:
{{{#!php
'meta_value_one',
'value' => 'meta_value_two',
'compare' => '>',
'type' => 'META_VALUE'
),
}}}
A workaround can be found [https://wordpress.stackexchange.com/a/164041 here] and [https://gist.github.com/mariovalney/e8646d8c64db36e9f239e6d05f2e5923 here] hahaha.
Feedback is welcome.",mariovalney
Tickets Awaiting Review,43324,query_vars is not necessarely representative of the final query_vars used to build the SQL query,,Query,,normal,normal,Awaiting Review,enhancement,new,,2018-02-14T23:53:57Z,2019-01-16T06:50:09Z,"I've recently stumbled upon a case here where the post_type query_var changes over the process of the query building process, and the change is not reflected in the query_vars variable of the query.
On the section highlighted [https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L2067-L2088 here] (sorry for pasting a GitHub link, i just wanted to use the section highlighting feature), you can see that if there's no post_type set in the query, but you're querying taxonomies (eg a tax archive query), the post_type is set (using a separate variable), and then used on the [https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L2345-L2366 following section] to build up the where statement.
In my opinion all of the query_vars modified during the process should be reflected in the query_vars variable, so you can after see the actual value being used for querying (on the {{{posts_request}}} filter for example).
You can see [https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L2152-L2160 here] a section where the {{{$q['author']}}, {{{$q['author__in']}}} and {{{$q['author__not_in']}}}. These is an example of changes that are not reflected in the query_vars (since there's no call to fill_query_vars after all this extra parsing, sanitizing, and defaulting process is made).
Let me know your thoughts.",msaggiorato
Tickets Awaiting Review,50154,About date and time request of version 5.4.1,,Query,5.4.1,normal,normal,Awaiting Review,feature request,new,,2020-05-13T08:33:12Z,2020-05-13T13:07:05Z,"In version 5.4.1, a single page template no longer applies if the year, month, day, hour, minute, and second are all specified as query parameters.
I understand that this is the effect of fixing a glitch that caused unauthenticated users to see private posts.
At the same time, it is disappointing that the traditional compatibility could not be maintained.
The following is the modified portion of the case, but I believe there is a fix that maintains traditional compatibility.
[47641]
The patch file is attached, so please check it.",tmatsuur
Tickets Awaiting Review,60490,Add 'author__in' option to WP_Query 'orderby' options,,Query,,normal,normal,Awaiting Review,feature request,new,,2024-02-09T18:31:07Z,2024-02-09T21:34:45Z,"I would like to be able to preserve the author ID order given in the WP_Query author_^^_in array.
This would work like how the orderby post_^^_in option works but for author_^^_in instead.
So, for example we already have:
'post_^^_in' – Preserve post ID order given in the post_^^_in array
And we'd be adding:
'author_^^_in' – Preserve author ID order given in the author_^^_in array
(https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters)
Would it be possible to add this option to WP Core?",bburgay
Tickets Awaiting Review,56168,Add a way easily perform advanced post fields queries,,Query,,normal,trivial,Awaiting Review,feature request,new,,2022-07-07T13:12:12Z,2022-07-07T13:12:12Z,"Currently if you want to perform advanced queries on the posts table you have to add your custom SQL to the query with the `posts_where` filter.
For example, let's say we want to get the next page with a `menu_order` value greater than the current page we would currently do something like:
{{{#!php
query['menu_order_gt'] ?? null;
if ( is_numeric( $value ) ) {
$where .= "" AND {$wpdb->posts}.menu_order > {$value} "";
}
return $where;
}, 10, 2 );
$query = new WP_Query( [
'post_type' => 'page',
'posts_per_page' => 1,
'menu_order_gt' => (int)get_post_field( 'menu_order' )
] );
}}}
I suggest adding a class like `WP_Meta_Query` but for post fields meaning we could achieve the same result as above but in a much cleaner and simpler way...
{{{#!php
'page',
'posts_per_page' => 1,
'field_query' => [
[
'field' => 'menu_order',
'value' => (int)get_post_field( 'menu_order' ),
'compare' => '>',
'type' => 'NUMERIC'
]
]
] );
}}}
",thelevicole
Tickets Awaiting Review,49057,Add tag for any WP_Query for simple access in pre_get_post action,,Query,,normal,normal,Awaiting Review,feature request,new,,2019-12-21T04:54:24Z,2019-12-21T04:54:24Z,"At current time it is difficult for find out which query is running at pre_get_post action
I offer add extra property to WP_Query as tag-name.
by this way i simply find out which query is running just by custom tag that added in any WP_Query object",hamedmoodi
Tickets Awaiting Review,39632,Adding Query identifier attribute,,Query,,normal,normal,Awaiting Review,feature request,new,,2017-01-18T19:55:17Z,2017-06-07T21:13:26Z,"You create any query by passing the arguments to `WP_Query`.
What will happen if we add the custom query identifier `_id` like this?
{{{#!php
'custom_name',
...
);
$q = new WP_Query( $args );
}}}
Nothing bad, and one good thing.
Using this `_id` I can work with filters like `posts_where` super easy.
This would work for many other filters from ''wp-includes/class-wp-query.php''
{{{#!php
query will hold the query arguments ...
if ( 'custom_name' == $q->query['_id'] ){
// do our improvement on $where
return $where.
}
return $where;
}
add_filter( 'posts_where', '_20170118_posts_where', 10 , 2 );
}}}
If you need more details here is the original [http://wordpress.stackexchange.com/questions/252246/how-to-detect-custom-query-inside-posts-where-hook/252406#comment375812_252406 example].
This already works, but we can benefit more if we add the `_id` for all WordPress core generated queries?
This should happen just after `WP_Rewrite` returns the query arguments, based on the query flags.
Let's test the future in case of main search query ( `$is_search` flag is true ).
You may write like this to address the search query:
{{{#!php
is_main_query() && $q->is_search() ){
... // do something with $where
}
return $where;
}}}
but with the `_id` '''main-search''' argument, you could write:
{{{#!php
get( '_id' ) ){
... // do something with $where
}
return $where;
}}}
This is somehow similar to the threads #15063 and #23833, but not exactly.
What would be the gain?
WordPress query programming may become simpler, and queries may be managed using '''human-readable''' names.
",prosti
Tickets Awaiting Review,53060,Data Deletion - comments,,Query,,normal,normal,Awaiting Review,feature request,new,,2021-04-19T16:44:31Z,2021-04-20T17:59:19Z,"**Data Deletion - comments**
Can we add a WP_Query parameter so that we can pull comments by author email or author user_id?
**Why?**
For better user privacy, I am creating a profile page for users where they can see all the comments they have made and easily delete those comments -- but in a post loop so that they have the context of the comments that they have made.
**Reference**
https://developer.wordpress.org/reference/classes/wp_query/#comment-parameters
It seems there is no WP_Query parameter for pulling posts by comment author. I think there should be for privacy.
Of course, I can make it happen the other way round with a custom DB query to find all comments by author and then get the post_id and loop the ids in_array but maybe it should be easier and more standard as to encourage user privacy respect.
",megphillips91
Tickets Awaiting Review,37837,Extend WP_Query author parameters to filter by role,,Query,4.7,normal,normal,Awaiting Review,feature request,new,,2016-08-26T10:25:01Z,2017-03-30T17:01:37Z,"WP_Query contains a series of author parameters (`author', ' author_name', ' author__in', and `author__not_in` as documented on the Codex).
It wpould be nice to add `author_role__in` and maybe `author_role__not_in` as valid parameters, and be able to also query for posts given one or a set of user roles. I can see a lot of usages, and this has indeed been asked inside the community in some places, although I could not find a Track dedicated ticket.
AFAIK, this would require the WP_Query database interaction to include the usermeta table, which can be expensive by default, and add a LIKE statement against the `wp_capabilities` usermeta field value, which is also expensive by default. So this might introduce performance problems and be discarded because of that. But otherwise, I would like that we consider this as a possible feature to add.",jadpm
Tickets Awaiting Review,43356,create is_403 function,,Query,4.9.3,normal,normal,Awaiting Review,feature request,new,,2018-02-19T13:48:04Z,2018-02-19T16:04:07Z,Create is_403() function and the ability to create a 403.php file in template to customize the page that visitors see when there try to access to a private content when there not loged in.,fabienlege
Unpatched Bugs,56312,Appending ?name to home URL shows the posts page instead of a static front page,,Query,,normal,normal,Future Release,defect (bug),reopened,,2022-07-30T10:45:09Z,2023-01-06T09:17:54Z,"I found something strange
I installed a WordPress then from setting . Reading I set a sample page as homepage
And when I opened website it was ok and showed content of sample page but when I added query string “?name” it showed latest blog posts
I tried everything as query string nothing did that and all showed sample page content and that was ok
Just just with ?name query string showed different thing
For ex localhost/site/?name show latest posts but
Localhost/site/?everythingyoutype
Was ok and show content of the page
Why ?name query string is like that??? I want to remove it
actually you must test it just on homepage of your site
not another pages
it hurts SEO if you show something else with query string on your site (specially on your homepage) instead of the main content
basically as you said when you enter the url of homepage with /?name you should see the homepage and nothing should change because it’s just a query string
I can show you an example
see this : https://amepro.at/
as you see everything is fine and homepage of website is ok
but please see this one https://amepro.at/?name
here you see the blog posts and it hurts SEO very bad
I got too much errors on search console with these kind of urls
Can you explan the logic behind it why should we show another thing like latest post when someone enter some parameter ?
it’s not normal at all",masimoti
Unpatched Bugs,15551,Custom post type pagination redirect,,Query,3.1,normal,normal,,defect (bug),reopened,,2010-11-23T21:50:06Z,2022-12-28T06:15:12Z,"We seem to be having a problem with a redirect on a custom post page (e.g., http://www.example.com/show/slug/).
Everything on the page shows correctly. The template pulls in posts with the following query:
{{{
'show', 'meta_value' => $show->ID, 'paged' => get_query_var('paged'), 'caller_get_posts' => true)); ?>
}}}
After the posts we display pagination links (e.g., http://www.example.com/show/slug/page/2/). In our rewrite rules, we include the following rule which should handle these URLs:
{{{
'show/([^/]+)/page/([0-9]{1,})/?$' => 'index.php?show=$matches[1]&paged=$matches[2]',
}}}
Instead of the page displaying and allowing us to pull in the second page of posts, the browser is being redirected back to the original page (http://www.example.com/show/slug/) with a 301. I see that this is happening inside the redirect_canonical function. The following code in wp-includes/canonical.php replaces /page/2/ with / causing the redirect:
{{{
// paging and feeds
if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
if ( !$redirect_url )
$redirect_url = $requested_url;
$paged_redirect = @parse_url($redirect_url);
while ( preg_match( ""#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#"", $paged_redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $paged_redirect['path'] ) || preg_match( '#/comment-page-[0-9]+(/+)?$#', $paged_redirect['path'] ) ) {
// Strip off paging and feed
$paged_redirect['path'] = preg_replace(""#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#"", '/', $paged_redirect['path']); // strip off any existing paging
$paged_redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $paged_redirect['path']); // strip off feed endings
$paged_redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $paged_redirect['path']); // strip off any existing comment paging
}
}}}",cbsad
Unpatched Bugs,60566,Posts Page as Draft remains publicly queryable,,Query,,normal,normal,Future Release,defect (bug),new,,2024-02-17T11:46:03Z,2024-02-19T11:04:08Z,"When assigning a Posts Page at ""WP Admin > Settings > Reading"" and afterward setting that page to draft, the page remains publicly queryable. This is possible via the `?page_id=` query (not `?p=`) and the provisioned slug.",Cybr
Unpatched Bugs,35758,Reading Settings fallback option when none is selected at Front page displays,,Query,4.4.1,normal,normal,,defect (bug),new,,2016-02-05T20:26:25Z,2019-06-04T20:54:56Z,"Hi,
I found a bug that makes the home page think it's a page. (I didn't look at the WP_Query variables.)
Here are the steps to replicate the issue:
1. Go to /wp-admin/options-reading.php
2. Delete the selected option at ""Front page displays"" through Developer Tools/Web Inspector.
3. Save settings.
4. Now no setting is selected.
The home page is a Posts Page but WP_Query doesn't recognize it as one, nor as a front page at all.
This causes all kinds of issues when plugins/themes rely on is_front_page().
Thanks!",Cybr
Unpatched Bugs,36966,Search is not working with soft hyphen symbols,,Query,4.5.2,normal,normal,,defect (bug),new,,2016-05-28T21:36:29Z,2019-06-04T20:59:30Z,"Site search doesn't work if a word contains soft hyphen symbols.
When a word is pretty long and it should fit within a limited space, the best solution seems to be to stuff it with soft hyphens (), so there will be no hanging lines.
It looks like this: Pseudopseudohypoparathyroidism
But in this case the word can't be found.",mvasin
Unpatched Bugs,23336,"Sticky Posts lack sanity bounding. If used too much, can severely degrade performance.",,Query,,normal,normal,,defect (bug),reopened,,2013-01-31T05:09:37Z,2019-06-04T20:43:50Z,"Came across an issue where a site was using sticky posts for a slider on the front page. The rest of the front page used custom taxonomy queries. As such, they'd mark items as sticky, have the slider grab the first three. Over years, they accumulated thousands of sticky posts, which, as you can imagine, made the front page of their site absurdly slow, as it was querying those thousands of posts every time.
Should we establish some sort of sanity limit here, to keep people from shooting themselves in the foot? I found this a REALLY hard issue to diagnose. Even with debug bar, there is no indication that sticky posts are being queried. There's just a giant WP_Query call that does a giant `IN()` query.
Something like a limit of 100 with FIFO would keep things from getting too crazy, without restricting people too much. If you have a need for more than that, you need to be using a taxonomy query.",markjaquith
Unpatched Bugs,35131,Unexpected 404: pending post hides published post with matching slug,,Query,4.3.1,normal,normal,,defect (bug),new,,2015-12-17T08:55:51Z,2019-06-04T20:53:40Z,"While attempting to recreate #35012 and #35031 I also noted the anomaly previously reported in #22902 where an authorized user could see all the posts displayed as if they were a single page.
Investigating this led me to determining that the existence of a new ""pending"" post with the same slug as an existing post prevents the user from visiting the existing post using its permalink.
Example:
post: 31766, status: pending, title: Cycle 1, slug: cycle-1 date: 2015-12-16 11:18:26
Content: You might be able to see this if you're logged in.
post: 31764, status: publish, title: Cycle 1, slug: cycle-1 date: 2015-12-16 11:17:17
Content: You should be able to see this.
Steps:
1. Create posts as above
2. Log out or otherwise visit the site as a visitor
3. View the blog page or the archive
4. Note that you see the published post, not the pending post
5. Click on the published post's permalink
6. You'll get a 404.
=== Expected result ===
Displays the published post.
=== Actual result ===
Displays a 404 page.
=== Explanation ===
- The query in WP_query returns two posts: 31766:pending and 31764:publish.
- Even though there are two posts in the result set, `is_single` is true.
- The logic to ""Check post status to determine if post should be displayed."" kicks in and the post array is emptied.
- This eventually leads to the 404.
=== My Conclusion ===
There are two problems leading to this one
1. The pending post should not have been given the same slug as the published post.
2. `is_single` should not have been set to true.
=== Proposed solution ===
If it's not possible to deal with the underlying cause then the logic in the ""Check post status..."" should be adjusted to filter out the posts that the user shouldn't have been able to see. If the resulting set contains more than one post then is_single should become false.
I noticed this on 4.4 but have reproduced it on 4.3.
I imagine the actual bug goes back a long long way.
",bobbingwide
Unpatched Bugs,38709,Unlimited query for invalid post names,,Query,4.6.1,normal,normal,Future Release,defect (bug),new,,2016-11-08T13:25:13Z,2024-01-31T21:38:38Z,"In case a request which is being parsed as one which sets a ""name"" query var (eg.: `http://localhost/wordpress-latest/2016/11/08/[` ) includes an invalid name ( the `[` ), a query without any limit with empty post_name is triggered:
{{{#!sql
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND ( ( YEAR( wp_posts.post_date ) = 2016
AND MONTH( wp_posts.post_date ) = 11
AND DAYOFMONTH( wp_posts.post_date ) = 8 ) )
AND wp_posts.post_name = ''
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
}}}
The problem with the query is that it matches all the drafts in the database, since they don't have the post_name set (is empty). This may have a performance implications for the database in case it contains a lot of drafts (or posts without the post_name set for any reason) as it queries all the posts.
The `post_name` is being set as empty due to `sanitize_title_for_query` in https://core.trac.wordpress.org/browser/tags/4.6.1/src/wp-includes/query.php#L2717
I have tested a more suitable validation function than `trim` ( eg.: `sanitize_title` ) in https://core.trac.wordpress.org/browser/tags/4.6.1/src/wp-includes/query.php#L1609 but it leads to archives being served on those invalid URLs, which does not seem like good fix.
Trying to set `posts_per_page` to 1 in case the `name` is parsed based on the rewrite rule (which seems like a good thing since we really should be interested in a single and unique post_name in such cases) hits a wall as the is_singular() returns true and the limit is not set even if the posts_per_page is present ( due to https://core.trac.wordpress.org/browser/tags/4.6.1/src/wp-includes/query.php#L3215 ).
So the fix might need to be more complicated than.",david.binda
Unpatched Bugs,36696,WP_Meta_Query can give wrong results when comparing large numbers,,Query,3.8.1,normal,normal,,defect (bug),new,,2016-04-28T02:23:43Z,2019-06-04T20:58:03Z,"This is a follow on from #27272.
Using quoted numbers can trigger MySQL to do floating-point type conversion (last two points in the first bullet list in http://dev.mysql.com/doc/refman/5.7/en/type-conversion.html):
> * If one of the arguments is a decimal value, comparison depends on the other argument. The arguments are compared as decimal values if the other argument is a decimal or integer value, or as floating-point values if the other argument is a floating-point value.
> * In all other cases, the arguments are compared as floating-point (real) numbers.
Currently number literals are quoted in `WP_Meta_Query`, whereas the LONGTEXT `meta_value` column is cast to the passed-in meta `type`. Thus when a number literal (quoted string) is compared to the `meta_value` column (cast to SIGNED/UNSIGNED meta `type`), floating-point type conversion is evoked. If the numbers involved are larger than the floating-point precision (53 bits), then incorrect comparisons can occur.
You can see this happening in the `mysql` client by using the 54 bit numbers 9007199254740992 (`0x20 0000 0000 0000`) and 9007199254740993 (`0x20 0000 0000 0001`):
{{{
select '9007199254740992'+0.0, '9007199254740993'+0.0, '9007199254740992'+0.0 < '9007199254740993'+0.0;
}}}
which will return:
{{{
+------------------------+------------------------+-------------------------------------------------+
| '9007199254740992'+0.0 | '9007199254740993'+0.0 | '9007199254740992'+0.0 < '9007199254740993'+0.0 |
+------------------------+------------------------+-------------------------------------------------+
| 9.007199254740992e15 | 9.007199254740992e15 | 0 |
+------------------------+------------------------+-------------------------------------------------+
}}}
(Note the results are system dependent.)
A way around this is to not quote number literals, as in the proposed patch, based on @wonderboymusic's [https://core.trac.wordpress.org/ticket/27272#comment:5 ""27272.2.diff""]. It's been switched (ahem) to an if-elseif-else statement to easily allow cases like `DECIMAL(10,2)` etc to be added. (Note the patch attached here also fixes a regression I introduced in previous proposed patches on the #27272 ticket re casting on `LIKE`/`NOT LIKE`.)
This issue relates to #36652 (using the PHP type of the meta `value` to determine cast), and the proposed patch should facilitate it.
This issue also relates to #36625 (don't bother `CHAR` casting `meta_value` column), and the proposed patch shouldn't impact on a fix for that.
",gitlost
Unpatched Bugs,35820,WP_Query(array( 'p' => 0)) will return posts,,Query,4.4.2,normal,normal,,defect (bug),new,,2016-02-12T21:28:16Z,2019-06-04T20:55:04Z,"Long to short, I was presuming that if the $args were such that no rows exist then WP_Query would return nothing.
Not so.
If by chance, 'p' => 0, you do get results.
Perhaps the 0 is interpreted as false? Even so, an ID == false should return no row, yes? Or one might argue ""well, that query doesn't make sense. it's not really valid."" again, all the more reason to return nothing.
",ChiefAlchemist
Unpatched Bugs,21790,When set a static front page WP main query isn't set correctly,SergeyBiryukov,Query,3.4.1,normal,normal,Future Release,defect (bug),assigned,,2012-09-04T13:50:26Z,2017-05-05T09:34:57Z,"In my project I use on several places pre_get_posts filter. When setting a static frontpage and blog page I get several notices on my screen. When I var_dump the main query the only value that is set it the page_id.
Even the post_type isn't set.",markoheijnen
Unpatched Bugs,27507,get_posts() not honoring post_status criteria,,Query,3.8.1,normal,normal,,defect (bug),new,,2014-03-25T05:49:53Z,2019-06-04T20:46:17Z,"Toss in the following in a mu-plugin file to reproduce:
{{{
$posts = get_posts();
var_dump($posts);
}}}
You'll get auto-drafts in the returned result set, instead of the expected published posts only (i.e. the default as set by `get_posts()`).
I've traced the problem to this loop that calls `get_post_stati()` in the `WP_Query#get_posts()` method:
{{{
foreach ( get_post_stati() as $status ) {
if ( in_array( $status, $q_status ) ) {
if ( 'private' == $status )
$p_status[] = ""$wpdb->posts.post_status = '$status'"";
else
$r_status[] = ""$wpdb->posts.post_status = '$status'"";
}
}
}}}
`get_post_stati()` latter relies on a global that isn't set yet. I'm suspicious that we should be calling it here to begin with. Assuming we should, I definitely don't think WP should silently return an empty array. It should cough a `_doing_it_wrong()` notice, and quite possibly even a warning.
That being said: why aren't the built-in post statuses registered by the time plugins get loaded? Can't we register them earlier? (And: does the same apply to custom post types?)",Denis-de-Bernardy
Unpatched Bugs,48860,get_queried_object return false when executed in parse_query hook,,Query,5.3,normal,normal,,defect (bug),reopened,,2019-12-03T08:47:53Z,2019-12-03T22:42:20Z,"When this function is executed in parse_query hook (i.e. woocommerce-perfect-seo-url) on author page ( /author/XXX/ ) it results with this notice.
{{{
#13 E_NOTICE: Trying to get property 'ID' of non-object
}}}
It's because 'author_name' is not converted into 'author' field in parse_query.
It's only used to mark page as ""is_author"".
{{{
if ( '' != $qv['author_name'] ) {
$this->is_author = true;
}
}}}
And get_queried_object relies on 'author' variable.
{{{
} elseif ( $this->is_author ) {
$this->queried_object_id = (int) $this->get( 'author' );
$this->queried_object = get_userdata( $this->queried_object_id );
}
}}}
",fliespl
Unpatched Bugs,31957,"query fails, when post is queried under specific name",,Query,4.1.1,normal,normal,,defect (bug),new,,2015-04-13T07:28:11Z,2019-06-04T20:49:30Z,"i.e., i have custom post type, named ""CARS"",
and when i have standard category, named ""CARS""..
when i publish '''standard''' post under ""cars"" category:
mysite.com/cars/something-name...
worpdress thinks, that it is under custom-post types, and 404 page is displayed..
to fix that, i have made this function:
{{{
//example URL: yoursite.com/cars/subcat/TORNADOO
add_action( 'pre_get_posts', 'myf' ); function myf( $query ) {
if ( $query->is_main_query() ) {
//when the PERMALINK was not found, then 404 maybe triggered.. But wait! maybe it is a standard post, under the standard category(which's name is i.e. ""cars"")
if (!url_to_postid(currentURL__MLSS)){
$link_array=explode('/','/cars/subcat/TORNADOO');
$k=array_filter($link_array); //remove empty values
$k=array_values($k); //reset hierarchy
$all_nmb = count($k);
//if post exists with the found slug(""TORNADOO""), lets check, if their parents are categories
$post=get_page_by_path(basename('TORNADOO'), OBJECT, 'post');
if ($post){
for($i=0; $i<$all_nmb-1; $i++){
$cat = get_term_by('slug', $k[$i], 'category');
if(!(in_category($cat->term_id,$post->ID) || post_is_in_descendant_category(array($cat->term_id),$post->ID))){
$failed=true; break;
}
}
if (!$failed){
//new query
$query->init();
$query->parse_query( array('post_type' =>'post') ) ;
//others
$query->is_home = false;
$query->is_single = true;
$query->is_singular = true;
$query->is_page = false;
$query->queried_object_id = $post->ID;
$query->set( 'page_id', $post->ID );
}
}
}
//if page exists with the that link, then query will be made correctly..
//$page=get_page_by_path(...., ..., 'page');
}
if ( ! function_exists( 'post_is_in_descendant_category' ) ) { function post_is_in_descendant_category( $cats, $_post = null ) {
foreach ( (array) $cats as $cat ) { $descendants = get_term_children( (int) $cat, 'category' );
if ( $descendants && in_category( $descendants, $_post ) ) {return true;}
}return false;
}
}
}}}
",selnomeria
Unpatched Bugs,46294,wp rest api fails to paginate page requests correctly when ordering on menu_order,,Query,5.4.1,normal,normal,Future Release,defect (bug),new,,2019-02-21T06:00:48Z,2021-04-12T21:58:19Z,"**Describe the bug**
Gutenberg and wordpress fails to render the parent page dropdown correctly when there are more than 100 pages and the pages have various menu_order values set.
The problem is that gutenberg calls the wordpress rest api like this, getting 100 items at a time.
http://server/wp-json/wp/v2/pages?per_page=100&exclude=890&parent_exclude=890&orderby=menu_order&order=asc&context=edit&_locale=user
http://server/wp-json/wp/v2/pages?per_page=100&exclude%5B0%5D=890&parent_exclude%5B0%5D=890&orderby=menu_order&order=asc&context=edit&_locale=user&page=2
This results in the following 2 sql queries:
`SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID NOT IN (890) AND wp_posts.post_parent NOT IN (890) AND wp_posts.post_type = 'page' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.menu_order ASC LIMIT 0, 100`
`SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID NOT IN (890) AND wp_posts.post_parent NOT IN (890) AND wp_posts.post_type = 'page' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.menu_order ASC LIMIT 100, 100`
When ordering on a non unique field like menu_order you need to also add a second unique ordering field like ID ,, See https://bugs.mysql.com/bug.php?id=72076 See the answer from Tor Didriksen.
This is very critical bug because it means that if the current pages parent is missing in the parent page dropdown and you click update it means that the menu order for that page will be reset and this means i cant use gutenberg.
**To Reproduce**
Steps to reproduce the behavior:
1. Create around 200 pages.
2. Set menu_order != on some of the pages.
3. edit any of the pages.
4. the parent page dropdown is missing pages
**Expected behavior**
the rest api should add some unique order by field to prevent the same items from coming on page 1 and 2 of the requests.
",hobzhobz
Unpatched Enhancements,34211,Ability to specify fields WP_Query can search,,Query,4.4,normal,normal,,enhancement,new,,2015-10-08T11:59:10Z,2019-06-04T20:52:08Z,"Currently the `s` parameter in WP_Query is hardcoded to only search in the `post_title` and `post_content` fields. A decent enhancement would be if you could also specify which postmeta fields it can search into as well.
Also allowing more fine-grained control so that it can search only postmeta fields and ignore `post_title` and `post_content` as well.
Something along the lines of:
{{{
's' => 'foo',
's_fields' =>'title',
's_meta_fields' => array( 'custom_field_1', 'custom_field_2' ),
}}}
`s_fields` can a string/array of either post_title and/or post_content. Setting it to false would disable searching these fields and assume you have set custom meta fields to search for instead. By default it would be `array( 'title', 'content' )`.
`s_meta_fields` can accept a string/array of postmeta field names to search for. By default it would be `false`.
A decent use case would be the [https://wordpress.org/plugins/search-by-sku-for-woocommerce/ Search by SKU for Woocommerce] plugin which resorts to writing a custom query.
I assume the only real concern would be performance.",paulwilde
Unpatched Enhancements,35761,Add filter(s) to get_adjacent_post function to change variables further down,,Query,,normal,normal,,enhancement,new,,2016-02-06T04:17:05Z,2019-06-04T20:55:03Z,"I'm finding it incredibly difficult to sort a post type using the existing filters to order by custom post meta alphabetically on a single post (for next/previous post).
A use case is when I have a separate field for a custom post type called ""Last Name"" where I would want my posts to display in alphabetical order by last name. When sorting on an archive with pre_get_posts, it's not a problem, however when navigating posts from the single post, there just doesn't appear to be a simple way to change the ""next"" and ""previous"" posts to maintain the same custom sort order when dealing with an alphabetical meta_value.
I'm proposing adding one or two filters to the get_adjacent_post() function which allows the final query to be filtered, or more importantly, the query result to be filtered so a custom sort can be implemented.",briandichiara
Unpatched Enhancements,35398,Allow post types to override `posts_per_archive_page`,,Query,,normal,normal,,enhancement,new,,2016-01-11T10:09:48Z,2019-06-04T20:54:10Z,fixed,sebastian.pisula
Unpatched Enhancements,20044,Enable search for pages by slug,,Query,3.7,normal,normal,,enhancement,new,,2012-02-14T22:17:58Z,2019-06-04T20:42:51Z,"Would be nice to be able to search a page by its slug. Might need to be a bit different depending on the permalink-strategy.
Steps to reproduce(with Post name-permalinks enabled):
1. Create a new page with a specific slug
2. Save page
3. Search for the exact slug-name
",ekitomat
Unpatched Enhancements,21096,Filter on is_front_page return value,,Query,,normal,normal,,enhancement,new,,2012-06-28T10:32:03Z,2019-06-04T20:43:16Z,"When you set a page (as 'placeholder' with same slug) as front page which is actually a post type archive to front page, is_front_page() will always return false on that page. The return value of the is_front_page() function is not filterable.
Attached patch adds this filter in the most basic way.",CoenJacobs
Unpatched Enhancements,25180,Make it possible to select only posts with comment_count > 0,,Query,3.6,normal,normal,,enhancement,new,,2013-08-29T17:03:00Z,2019-06-04T20:44:44Z,May need this when #11398 goes in.,wonderboymusic
Unpatched Enhancements,38173,Meta query creates unecessary multiple left joins when using the same meta key,,Query,3.2,normal,normal,Future Release,enhancement,new,,2016-09-27T16:36:27Z,2017-02-17T03:06:46Z,"If you specify the below as a meta_query wordpress creates an extremely bad and inefficient query, it seems to unnecessarily create a left join for each array even though they have the same key when it could use the same join
{{{#!php
'OR',
array(
'key' => 'product',
'value' => '1',
'compare' => '!='
),
array(
'key' => 'product',
'compare' => 'NOT EXISTS'
)
);
}}}
{{{
SELECT SQL_CALC_FOUND_ROWS vvc_posts.ID FROM vvc_posts LEFT JOIN vvc_postmeta ON ( vvc_posts.ID = vvc_postmeta.post_id ) LEFT JOIN vvc_postmeta AS mt1 ON (vvc_posts.ID = mt1.post_id AND mt1.meta_key = 'product' ) WHERE 1=1 AND (
( vvc_postmeta.meta_key = 'product' AND CAST(vvc_postmeta.meta_value AS CHAR) != '1' )
OR
mt1.post_id IS NULL
) AND vvc_posts.post_type = 'news' AND ((vvc_posts.post_status = 'publish')) GROUP BY vvc_posts.ID ORDER BY vvc_posts.post_date DESC LIMIT 0, 10
}}}
On my site this query takes a huge 6.640 sec, more than 80% of the page's ttfb.
{{{
SELECT SQL_CALC_FOUND_ROWS vvc_posts.ID
FROM vvc_posts
LEFT JOIN vvc_postmeta ON ( vvc_posts.ID = vvc_postmeta.post_id && vvc_postmeta.meta_key = 'product')
WHERE 1=1
AND (CAST(vvc_postmeta.meta_value AS CHAR) != '1' OR vvc_postmeta.post_id IS NULL )
AND vvc_posts.post_type = 'news'
GROUP BY vvc_posts.ID
ORDER BY vvc_posts.post_date
}}}
whereas an optimized version takes only 0.969 sec.",neonWired
Unpatched Enhancements,36670,Move CAST to right-hand side of comparison in meta query,,Query,3.1,normal,normal,,enhancement,new,,2016-04-26T04:40:41Z,2019-06-04T20:57:40Z,"The SQL clause created by a meta query [https://github.com/WordPress/WordPress/blob/4.5/wp-includes/class-wp-meta-query.php#L634 CASTs the column value] `postmeta.meta_value` and compares it to the value provided in the meta query, a la `CAST(postmeta.meta_value AS CHAR) = 'some-value'`.
Casting a column value instead of a constant means that MySQL will ignore an index for that column if one exists. Although core does not define an index for the `meta_value` column, a user could create one for perf reasons.
Switching the side of the CAST would result in the same two types, just on different sides
`postmeta.meta_value = CAST('some-value' AS CHAR)`
That means [http://dev.mysql.com/doc/refman/5.7/en/type-conversion.html MySQL's type conversion] will work the same as it did previously.
#36649 would need to be completed before this.
Related: #27272, #36625",ericlewis
Unpatched Enhancements,49555,Reorder WP_Query methods for a more logical placement,,Query,,normal,trivial,Future Release,enhancement,new,,2020-03-01T18:03:01Z,2020-03-01T18:22:05Z,"Conditional tag functions were initially ordered alphabetically in the source files. With some changes over the years, new functions were introduced and placed next to the closest related function. Now the order is mixed, and the placement of some individual functions like `is_month()` makes no sense in the overall structure.
It would be helpful if the methods were ordered in a more logical manner, perhaps based on the [https://developer.wordpress.org/reference/classes/wp_query/#parameters Parameters] section of the DevHub reference, though that could also use some improvement.
For the record, the current order is as follows:
||=In `wp-includes/query.php`=||=In `wp-includes/class-wp-query.php`=||
||`is_archive()`||`::is_archive()`||
||`is_post_type_archive()`||`::is_post_type_archive()`||
||`is_attachment()`||`::is_attachment()`||
||`is_author()`||`::is_author()`||
||`is_category()`||`::is_category()`||
||`is_tag()`||`::is_tag()`||
||`is_tax()`||`::is_tax()`||
||(moved to `deprecated.php`)||`::is_comments_popup()`||
||`is_date()`||`::is_date()`||
||`is_day()`||`::is_day()`||
||`is_feed()`||`::is_feed()`||
||`is_comment_feed()`||`::is_comment_feed()`||
||`is_front_page()`||`::is_front_page()`||
||`is_home()`||`::is_home()`||
||`is_privacy_policy()`||`::is_privacy_policy()`||
||`is_month()`||`::is_month()`||
||`is_page()`||`::is_page()`||
||`is_paged()`||`::is_paged()`||
||`is_preview()`||`::is_preview()`||
||`is_robots()`||`::is_robots()`||
||`is_favicon()`||`::is_favicon()`||
||`is_search()`||`::is_search()`||
||`is_single()`||`::is_single()`||
||`is_singular()`||`::is_singular()`||
||`is_time()`||`::is_time()`||
||`is_trackback()`||`::is_trackback()`||
||`is_year()`||`::is_year()`||
||`is_404()`||`::is_404()`||
||`is_embed()`||`::is_embed()`||
||`is_main_query()`||`::is_main_query()`||",SergeyBiryukov
Unpatched Enhancements,36309,Timezone issue in WP_Date_Query->build_mysql_datetime,,Query,4.4.2,normal,normal,,enhancement,new,,2016-03-23T15:57:00Z,2019-06-04T20:56:04Z,"Currently build_mysql_datetime function in WP_Date_Query using gmdate to generate SQL datetime.
{{{#!php
false` and `update_post_term_cache => false` means using `WP_Query` still produces two queries.
Also, it would be interesting to compare the performance of `SQL_CALC_FOUND_ROWS` vs `COUNT(*)` when all you care about is the total count.",danielbachhuber
Unpatched Enhancements,29823,WP_Date_Query across tables,boonebgorges*,Query,,normal,normal,,enhancement,accepted,,2014-10-02T00:29:17Z,2019-06-04T20:47:50Z,"The changes proposed in #29822 will make it possible to think about cross-table date queries. Things like: all posts from 2011 that have comments from 2013 or later.
Using this ticket as a placeholder for ideas regarding syntax (do we allow table names to be passed as a param? or perhaps a 'type' argument like `WP_Meta_Query` has, which is then translated into table names?) and other discussion.",boonebgorges
Unpatched Enhancements,31083,WP_date_Query does not validate string values of 'before' or 'after',,Query,4.1,normal,normal,,enhancement,new,,2015-01-21T08:18:57Z,2019-06-04T20:48:45Z,"Currently the ''before/after'' values in ''WP_Date_Query'' can be an array or string, which will be parsed by strtotime:
{{{
if ( ! is_array( $datetime ) ) {
// @todo Timezone issues here possibly
return gmdate( 'Y-m-d H:i:s', strtotime( $datetime, $now ) );
}
}}}
But we don't validate this string in ''validate_date_values'':
{{{
if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ){
$valid = $this->validate_date_values( $date_query['before'] );
}
}}}
----------------------
Example:
{{{
$query_args = array(
array( 'before' => 'i am a valid date string!?' )
);
$date_query = new \WP_Date_Query( $query_args );
echo $date_query->get_sql;
// AND ( ( post_date < '1970-01-01 00:00:00' ) )
}}}",ChriCo
Unpatched Enhancements,26937,get_adjacent_post() should use WP_Query rather than build its own SQL query,nacin,Query,3.7,normal,normal,Future Release,enhancement,reopened,,2014-01-25T18:51:47Z,2018-01-31T20:33:04Z,"With the introduction of the `WP_Date_Query` through r25139, `get_adjacent_post()` no longer needs to build its own SQL to retrieve adjacent posts. By switching to `WP_Query`, we gain the benefit of its performance improvements, including native caching.
The trickiest part of this change is maintaining support for the `get_{$adjacent}_post_join` and `get_{$adjacent}_post_where` filters currently applied to the SQL built in `get_adjacent_post()`.",ethitter
Unpatched Enhancements,15068,merging query objects/arrays,,Query,3.0,normal,normal,,enhancement,new,,2010-10-08T04:27:58Z,2019-06-04T20:41:30Z,"As multiple post type installations proliferate, I assume more and more people will come across a situation (like me) in which they need to display two (or more) sets of content units, say posts, and post-type ""audio"" in one stream - say on the main blog page. As long as the only condition is the post type itself, that will work fine. However, if those two sets need to be selected using different conditional criteria, say a category in one case, and a custom field in the other, then the current query_posts options will not be sufficient.
While it is possible to retrieve multiple arrays via get_posts and merge them, then sort them using cusomt php, such a solution will break the paged navigation.
If such situations will - as I assume - become more likely as more people use multiple post types and additional variables to specify content, I think it would be useful to be able to combine multiple queries into a meta query that will sort the combined object according to a common sorting variable, say date, and thus preserve the paged navigation.
",youngmicroserf
Unpatched Enhancements,19738,meta_query should check for wildcards when using LIKE operator,,Query,3.2,normal,normal,,enhancement,reopened,,2012-01-04T18:35:04Z,2019-06-04T20:42:41Z,"This seems intentional, but when using the LIKE operator in a meta query, the % wildcards are automatically added to the start and end of the value when generating the SQL.
I think a more robust way of doing this would be to only add said wildcards if one cannot be found within the value itself. ",ejdanderson
Unpatched Enhancements,11398,new sort method for query_posts (order by last comment date),,Query,2.9,normal,normal,,enhancement,assigned,,2009-12-11T15:44:42Z,2019-06-04T20:40:57Z,"I think we need sorting by latest post comment ability for query_posts. ""Recent comments"" plugins does this but we need this sorting in the core.
BBPress is planned as a WP plugin according latest chat logs posted by Matt. We gonna have to need this anyway.",erden.ozkan
Unpatched Enhancements,37056,paginate_links should be a method on WP_Query,,Query,4.6,normal,normal,,enhancement,new,,2016-06-08T22:21:09Z,2019-06-04T21:00:17Z,"How do we paginate custom or subqueries when `paginate_links` relies upon the global `$wp_query` variable?
It's easy. We make `paginate_links` a method on the `WP_Query` object. Then the function `paginate_links` can rely upon the method. Likewise with `get_the_posts_pagination`, with a way to pass query context.
I'll get around to a patch when I can.",jfarthing84
Unpatched Enhancements,31383,Add WP_Tax_Query support to WP_User_Query,,Query,4.2,normal,normal,Future Release,feature request,new,,2015-02-19T16:31:15Z,2024-01-02T10:46:44Z,"Users like any other object type in WordPress can have taxonomy terms assigned to them. However, there is currently no way to query by taxonomies in WP_User_Query.
As far as I could find, the only way to really accomplish this right now is to use get_objects_in_term(), filter out the non user objects, and then use the include parameter.
Ideally, I think you should be able to accomplish this by the following:
{{{
$user_query = new WP_User_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'tax_name',
'field' => 'slug',
'terms' => array( 'term-1', 'term-2' ),
)
)
) );
}}}",desrosj
Unpatched Enhancements,16910,Lazy evaluation for WP_Query,,Query,,normal,normal,,feature request,new,,2011-03-21T01:04:39Z,2019-06-04T20:41:58Z,"Suppose we have a 'city' post type, which is associated with a 'country' post type, such that each 'city' post has a 'country' parent post.
Then the 'country' CPT has a 'language' taxonomy associated to it.
Now, let's say we want to find all the cities which speak a certain language.
Let's assume we already have the `'post_parent__in'` query var: #13927
We could construct a two-step query, like this:
1) Get all the countries with that language:
{{{
$country_ids = get_posts( array(
'fields' => 'ids',
'post_type' => 'country',
'language' => 'french',
'nopaging' => true
) );
}}}
2) Get all the cities belonging to that country:
{{{
$cities = get_posts( array(
'post_type' => 'city',
'post_parent__in' => $country_ids
) );
}}}
No custom SQL queries; fantastic!
But, if you have many many countries (not a good example, I know), you waste a lot of time passing the IDs back and forth from PHP to SQL.
Final query:
{{{
SELECT *
FROM wp_posts
WHERE post_type = 'city'
AND post_parent IN (1, 2, 3, ...)
}}}
It would be a lot more scalable to put the first query into the second, directly, as a subquery.
So, it would now look like this:
1) Get all the countries with that language:
{{{
$country_ids = get_posts( array(
'fields' => 'ids',
'post_type' => 'country',
'language' => 'french',
'nopaging' => true,
'lazy' => true'
) );
}}}
2) Get all the cities belonging to that country:
{{{
$cities = get_posts( array(
'post_type' => 'city',
'post_parent__in' => $country_ids
) );
}}}
$country_ids would now be a WP_Lazy_Query object, which would just contain the subquery SQL. It would be appended to the second query, when needed:
Final query:
{{{
SELECT *
FROM wp_posts
WHERE post_type = 'city'
AND post_parent IN (
SELECT ID
FROM wp_posts
WHERE post_type = 'country'
INNER JOIN wp_terms ...
)
}}}",scribu
Unpatched Enhancements,30982,Meta query in pre_get_posts,,Query,4.1,normal,normal,,feature request,new,,2015-01-11T20:36:44Z,2019-06-04T20:48:32Z,"I don't know if it is already in place, but I want to add in the hook ""pre_get_posts"" custom field. In the page ""search.php"", I want to search ""example"" in post_title, content and custom field in all pages, posts and post-type.
But this is the code I put in the hook :
{{{
function recherche_avancee( $query ) {
if ( !is_admin() && $query->is_search ) {
$custom_fields = array(
""introduction"",
""ensavoirplus""
);
$meta_query = array('relation' => 'OR');
foreach($custom_fields as $cf) {
array_push($meta_query, array(
'key' => $cf,
'value' => $_GET['s'],
'compare' => 'LIKE'
));
}
$query->set(""meta_query"", $meta_query);
}
}
add_action( 'pre_get_posts', 'recherche_avancee');
}}}
and this is the SQL code I get :
{{{
1. SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
2. FROM wp_posts
3. INNER JOIN wp_postmeta
4. ON ( wp_posts.ID = wp_postmeta.post_id )
5. WHERE 1=1
6. AND (((wp_posts.post_title LIKE '%exemple%')
7. OR (wp_posts.post_content LIKE '%exemple%')))
8. AND wp_posts.post_type IN ('post', 'page', 'attachment')
9. AND (wp_posts.post_status = 'publish'
10. OR wp_posts.post_status = 'miseenavant'
11. OR wp_posts.post_author = 3)
13. AND ( ( wp_postmeta.meta_key = 'introduction'
14. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%exemple%' )
15. OR ( wp_postmeta.meta_key = 'en_savoir_plus_page'
16. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%exemple%' ) )
17. GROUP BY wp_posts.ID
18. ORDER BY wp_posts.menu_order ASC
19. LIMIT 0, 10
}}}
I want to add the line 13, 14, 15, 16 on the top on the code after the search in the content and the title. And I don't want a '''AND''' before the line 13 but a '''OR'''.
But here's the SQL I would need :
{{{
1. SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
2. FROM wp_posts
3. INNER JOIN wp_postmeta
4. ON ( wp_posts.ID = wp_postmeta.post_id )
5. WHERE 1=1
6. AND (((wp_posts.post_title LIKE '%exemple%')
7. OR (wp_posts.post_content LIKE '%exemple%')
8. OR ( wp_postmeta.meta_key = 'introduction'
9. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%exemple%' )
10. OR ( wp_postmeta.meta_key = 'en_savoir_plus_page'
11. AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%exemple%' ))
12. AND wp_posts.post_type IN ('post', 'page', 'attachment')
13. AND (wp_posts.post_status = 'publish'
14. OR wp_posts.post_status = 'miseenavant'
15. OR wp_posts.post_author = 3)
16. GROUP BY wp_posts.ID
17. ORDER BY wp_posts.menu_order ASC
18. LIMIT 0, 10
}}}
Is it possible to do this now? If this is not the case, is it possible to consider it in the ""future""?
Hope this is not already proposed ...
Thank you for reading :-)",Spidlace
Candidates for Closure,35476,Allow posts to be filtered before return when `fields` parameter is used with `WP_Query`,adamsilverstein*,Query,,normal,normal,Awaiting Review,enhancement,accepted,close,2016-01-15T16:46:59Z,2023-09-19T21:10:23Z,"Right now, when the '''fields''' parameter is used with '''WP_Query''' (""ids"" or ""id=>parent""), the returned posts are not filterable at all. Later in WP_Query, the_posts can be used to filter returned posts. This functionality should be mimicked with fields queries.
The use case for this is in plugins that bypass MySQL in WP Query (Elasticsearch). Fields queries right now can not be bypassed.
Patch attached.",tlovett1
Candidates for Closure,58600,wp_query Enhancement,,Query,6.2,normal,normal,Awaiting Review,feature request,new,close,2023-06-22T13:21:56Z,2023-07-03T16:51:04Z,"I wolud like to enhance the wp_query to retrive post base on catgory orders.
Category Ex. with post
Mobile -: Post-1, Post-3, Post-6
Appliance -: Post-2, Post-8, Post-10
I Need Posts like in this order using wp_query of order by category ASC/DESC
Current output is according to ID order
Post-1
Post-2
Post-3
Post-6
Post-8
Post-10
Expected output
Post-2
Post-8
Post-10
Post-1
Post-3
Post-6",thakordarshil
Slated for Next Release,59442,Duplicate query in WP_Query,,Query,6.2,normal,normal,6.6,defect (bug),assigned,dev-feedback,2023-09-25T11:32:47Z,2024-03-13T15:27:55Z,"When a site using a classic theme and has sticky posts, that can result in duplicate query. ( See attached screenshot ). This is because post_type variable passed the sticky sub query, is empty string on the first run. See the [https://github.com/WordPress/wordpress-develop/blob/de9e06a4c021295af3ac11fdd08ea29a57529668/src/wp-includes/class-wp-query.php#L3493 line]. This results in different cache query key being generating, resulting in duplicate queries.
Steps to replicate.
1. Set theme to 2016.
2. Import theme data test data.
3. Go to home page.
4. Open query monitor, see duplicate query. ",spacedmonkey
Tickets Awaiting Review,45343,$query->post is null when WP_Query `fields` parameter is present,,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2018-11-14T08:07:12Z,2018-11-14T10:23:21Z,"Normally, WP_Query returns an object where `$query->posts` contains an array of posts and `$query->post` contains the first post. But if the `fields` parameter is present then `$query->post` returns `null`. Is it a bug or an expected behaviour? If it's expected then it should be documented because it's confusing and unintuitive.
**Example:**
{{{#!php
'my-post-type',
]);
if ($query->have_posts()) {
$firstPost = $query->post; // returns the same as $query->$posts[0]
}
// Weird behaviour
$query = new \WP_Query([
'post_type' => 'my-post-type',
'fields' => 'ids',
]);
if ($query->have_posts()) {
$firstPost = $query->post; // returns null
}
",wujek_bogdan
Tickets Awaiting Review,57678,Missing use of placeholders and $wpdb->prepare(),,Query,,normal,major,Awaiting Review,defect (bug),new,dev-feedback,2023-02-09T08:59:21Z,2023-02-27T06:51:26Z,"Use placeholders and $wpdb->prepare(); found interpolated variable $prefix at ""SELECT $prefix""
**file path:** wordpress/wp-admin/setup-config.php
**Line Number:** 325
",mahekkalola
Tickets Awaiting Review,33341,WP_Meta_Query IN operator with empty array does not return expected result,,Query,3.2,normal,critical,Awaiting Review,defect (bug),reopened,dev-feedback,2015-08-11T18:32:26Z,2023-10-17T19:18:10Z,"When using the `IN` compare mode in a `WP_Meta_Query` where the value is an empty array, this query is evaluated with an unexpected behavior.
For example, I have some posts with a meta field called `'some-textfield'`:
{{{
$posts = get_posts( array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'some-textfield',
'value' => array(),
'compare' => 'IN',
),
),
) );
}}}
This code returns all posts although I would rather expect it to return no posts at all since the value of `'some-textfield'` (whatever it may be) is not ''in'' those provided in the `value` field.
I discovered it when I needed to perform a meta query where the value was an array that was returned by a previous operation. It is obviously a minor issue since we can simply check if the array is empty (and in that case do not make the query at all) - but I thought it's not really the expected result of such a query.
The solution would be to:
* ignore this condition if the `relation` is set to `OR` and there are other conditions available
* evaluate this condition to false otherwise (and thus return no results)",flixos90
Tickets Awaiting Review,50871,"When exact is true and orderby set to relevance, there is a DB error on search results page",,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2020-08-06T20:21:56Z,2020-08-07T16:18:15Z,"In search query, when `exact` is set to `true` and `orderby` set to `relevance` there is DB error
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DESC, wp_posts.post_date DESC LIMIT 0, 10' at line 1]
`SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE 'hello') OR (wp_posts.post_excerpt LIKE 'hello') OR (wp_posts.post_content LIKE 'hello'))) AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') ORDER BY DESC, wp_posts.post_date DESC LIMIT 0, 10`
It is clear that both options together has no meaning. But it is compatibility issue between [https://wordpress.org/plugins/wp-extended-search/ WP Extended Search] and [https://wordpress.org/plugins/woocommerce/ WooCommerce]
WP Extended search has a feature to match exact sentence so it sets `exact` to `true` and later WooCommerce adds `orderby => relevance` causing this SQL error.
=== How to reproduce with just WP
* Add this code to theme or plugin
{{{#!php
set( 'exact', true );
$query->set( 'orderby', 'relevance' );
$query->set( 'order', 'DESC' );
});
}}}
* Go to front-end and make a search, you will see the error.
=== Proposed fix
Here https://core.trac.wordpress.org/browser/tags/5.4.2/src/wp-includes/class-wp-query.php#L2357
We checking if `! empty( $q['search_orderby_title'] )` is not empty but we allow to call `parse_search_order()` when `'relevance' === $q['orderby']` causing `ORDER BY DESC` in SQL query without column name.
IMHO, we should not call `parse_search_order()` when `search_orderby_title` is empty regardless of `orderby`.",5um17
Tickets Awaiting Review,43238,`suppress_filters` not set in `pre_get_posts` hook,,Query,4.9.4,normal,normal,Awaiting Review,defect (bug),reopened,dev-feedback,2018-02-06T21:56:46Z,2022-05-13T09:56:29Z,"After updating to 4.9.4 my media library is empty locally and on my server. I confirmed this on a handful of sites that I have updated.
I cleared the cache and also checked the console.
I don't see any errors or any ajax requests being made.
The /wp-json/wp/v2/media does however contain a response with media.
Locally I am running latest OSX, my server is Ubuntu 16.04 both with PHP ~7.0",adampatterson
Candidates for Closure,50070,'post_type' query variable not set for taxonomy queries,,Query,5.4,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2020-05-03T17:12:19Z,2020-05-27T20:56:06Z,"When a standard taxonomy query is executed on the front-end (for example loading a category term archive page to see all posts associated with that term), the `$wp_query` object constructed in the `get_posts()` function omits the `post_type` query variable.
The `$q['post_type']` is empty initially (line 1848 wp-includes/class-wp-query.php), however, when the query is identified as a taxonomy query, a search is done to find which post_type is registered with this taxonomy (line 2132 wp-includes/class-wp-query.php) and the `$post_type` is set within the scope of the function, but the referenced query variable `$q['post_type']` isn't updated.
this causes a problem to identify queries when hooking filters such as `posts_orderby` / `posts_where` / `posts_join`
",aurovrata
Candidates for Closure,44848,Ensure that empty author profiles have proper 404 behaviour,,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2018-08-27T14:33:38Z,2019-09-17T19:09:53Z,"** Summary **
- WordPress 'creates' a ''profile posts archive'' (i.e., ""See all posts by [author name]"") for each user in the system. This can be reached by clicking 'view' from the Users table in wp-admin.
- It does so, ''even if they have no posts'' - and even if they lack the permission to publish posts entirely.
- Whilst the empty profile pages ''look'' like they serve a standard 404 error, in fact, they return a 200 HTTP header status, and just call the 404 template part for the main page body.
- This results in many 'soft 404' pages/errors, which can adversley impact the way in search engines and other systems (Facebook, Twitter, etc) crawl, extract information from, and value/evaluate websites (see Google's documentation on soft 404s at https://support.google.com/webmasters/answer/181708?hl=en).
It's important that we correct this behaviour in WordPress Core for numerous reasons; from compliance with basic web standards (error pages should return an appropriate HTTP header status), to adherence with the guidelines and preferences of external platforms (search engines, social networks, etc), to consistency with other page/template handling processes.
** Example **
A newly created `subscriber` user on a test site (called 'Test User 2') with no authored posts has an author archive accessible at https://yoast.jonoalderson.com/author/test-user-2/. Although this presents as a 404 error, the page returns meta data and behaviour consistent with a valid author request (see the tags contained in the `` of the HTML source; particularly the `` tags). The body template then just calls the 404 template part.
** Solution **
We should ensure that these scenarios return proper/consistent 404 behaviour.
Specifically, requests to author profiles where the author has zero posts should trigger normal 404 behaviour (including headers, query behaviour, etc), as opposed to just calling the 404 template.
E.g.,
{{{
// If author archive has zero posts
global $wp_query;
$wp_query->set_404();
status_header(404);
include( get_query_template( '404' ) );
die();
}}}
As opposed to just:
{{{
// If author archive has zero posts
include( get_query_template( '404' ) );
die();
}}}
",jonoaldersonwp
Candidates for Closure,52921,If page content blank and any page shows 404 error,,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2021-03-26T10:53:11Z,2021-03-30T01:31:53Z,"If not add any content in the page default content area from the admin panel and save the page and then view the page it shows 404page not found. If add any content in the content area and save then view the page, it's working fine.
https://ngatiwhatuaorakei.com/ ",ujjwalghosh
Candidates for Closure,58515,Need to use $wpdb->prepare instead of sprintf,,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2023-06-12T13:04:00Z,2023-06-22T07:25:46Z,"Need to use $wpdb->prepare instead of sprintf in ""_prime_comment_caches"" functions.
File: wp-includes/comment.php",hiren1094
Candidates for Closure,44349,Posts show up multiple times in backend when they have the exact same date,,Query,4.9.6,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2018-06-11T15:46:38Z,2022-02-09T08:19:52Z,"When I import for example 200 posts with the Import WordPress tool and then go to wp-admin>posts, the posts show up in the query multiple times (for instance on page 1 and page 2). Seems like others are left out.",wzshop
Candidates for Closure,48078,Some WP_XXX_Query::query() methods produce incorrect results when called in a loop,,Query,,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2019-09-19T18:28:19Z,2019-09-20T11:47:58Z,"While testing a [https://core.trac.wordpress.org/attachment/ticket/37392/37392.9.patch patch] for #37392 I came across what ''may'' be a bug in `WP_Site_Query::query()`.
That patch creates a `WP_Site_Query` object and then in a loop does various different `query()`'s, as in:
{{{#!php
$q = new WP_Site_Query();
$args = array(
'network_id' => $network_id,
'number' => 1,
'fields' => 'ids',
'no_found_rows' => false,
);
foreach ( array( 'public', 'archived', ... ) as $status ) {
$_args = $args;
$_args[ $status ] = 1;
$q->query( $_args );
// do something with the results of this site query.
}
}}}
However, calling `query()` in a loop like that doesn't produce the expected results other than the 1st time through the loop.
Why? Because when `query()` calls `WP_Site_Query::get_site_ids()` on subsequent iterations, the protected class member `$sql_clauses` still has its value from the previous iteration through the loop and the ""new"" query basically gets added to the previous queries.
In the case of the above code this results in the query for `archive = 1` to actually be `public = 1 AND archive = 1` which is **not** what is intended.
Looking at other `WP_XXX_Query()` classes, I ''think'' the following suffer from the same thing (although I haven't written code to test that):
1. `WP_Network_Query`
2. `WP_Term_Query`
but the following do **not**:
1. `WP_Query` (because it doesn't use a class member for the clauses)
2. `WP_User_Query` (because it uses a `prepare_query( $query )` method which resets the class member(s))
So, I guess the question is: should these `query()` methods be expected to work when called multiple times in a loop (with different queries each time) or is that **not** an intended use?",pbiron
Candidates for Closure,39945,WP_Query::get_posts fails to correctly sanitize 'posts_per_page',,Query,4.7.2,normal,normal,Awaiting Review,defect (bug),new,dev-feedback,2017-02-22T21:34:01Z,2020-03-03T22:32:24Z,"WP_Query::get_posts fails to correctly sanitize the 'posts_per_page' argument when a negative value in range (-2, -1) is supplied.
== Example ==
The following get_posts query causes an exception:
{{{
get_posts(array('posts_per_page' => '-1.5'));
}}}
Exception: WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1' at line 1 for query SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 0, -1 made by get_posts, WP_Query->query, WP_Query->get_posts
== Cause ==
Incomplete sanitization in WP_Query::get_posts(), line 1775 - 1779:
{{{
$q['posts_per_page'] = (int) $q['posts_per_page'];
if ( $q['posts_per_page'] < -1 )
$q['posts_per_page'] = abs($q['posts_per_page']);
elseif ( $q['posts_per_page'] == 0 )
$q['posts_per_page'] = 1;
}}}
== Impact ==
Some plugins (e.g. Woocommerce) initialize the posts_per_page argument with user supplied values and may suffer from an information disclosure vulnerability, depending on the webserver configuration.
Confirmed on the latest Wordpress version 4.7.2.
First reported at 19.02.2017 to security[at]wordpress.org without response (not nice!), so I assume you do not consider this security relevant in accordance with e.g. https://make.wordpress.org/core/handbook/testing/reporting-security-vulnerabilities/#why-are-there-path-disclosures-when-directly-loading-certain-files",biisent
Candidates for Closure,48193,Improve the WordPress loop,,Query,,normal,normal,Awaiting Review,enhancement,new,dev-feedback,2019-10-01T18:53:57Z,2024-01-20T15:01:13Z,"Currently, there are a number of ways that the ""loop"" can be handled in WordPress. Each depends on whether you are using the WP_Query global, a custom WP_Query instance, or an array of posts.
I propose that we add a PHP 5.6+ compatible generator function called `wp_loop()` that will simplify all of these use cases into a single, more modern approach. See [https://wpscholar.com/blog/creating-better-wordpress-loop/]",wpscholar
Candidates for Closure,49429,There seems to be no way to check query value for NULL,,Query,5.3.2,normal,normal,Awaiting Review,enhancement,new,dev-feedback,2020-02-14T04:56:53Z,2020-02-14T12:29:13Z,"NOT EXISTS and EXISTS both don't do what I want
I want to check `WHERE meta_value IS NOT NULL`
exists does this, applied to meta field
related_post_id2:
`
""where"" ""mt5.meta_key = 'related_post_id2'""
""join"" "" INNER JOIN wp_2_postmeta AS mt5 ON ( wp_2_posts.ID = mt5.post_id )""
`
that is not what I want
NOT EXISTS does:
`
""where"" ""mt5.post_id IS NULL""
""join"" "" LEFT JOIN wp_2_postmeta AS mt5 ON (wp_2_posts.ID = mt5.post_id AND mt5.meta_key = 'related_post_id2' )""
`
well, thats not what I want either, because now it checks ""if there is a row with related_post_id2"".
I want
""A row where the meta_value is not null""
in reality what I want is
Any entry, that has:
No value for related_post_id2
empty string for related_post_id2
or
null for related_post_id2
does that make sense?
",Jossnaz
Tickets Needing Feedback,47719,"Consistency issue with `include` parameter set to ""0"" in `WP_Term_Query`",SergeyBiryukov,Query,,normal,normal,Future Release,defect (bug),reviewing,dev-feedback,2019-07-17T09:10:48Z,2021-02-17T07:24:39Z,"There is a consistency issue with `include` parameter when used in `WP_Term_query`.
If `include` is set to/contains `[0]`, the query returns all terms.
This is not consistent with other query classes, like `WP_query` (using corresponding `post_in` parameter) and even more like `WP_User_query` (using the same `include` parameter).
Those doesn't return any result.
See reproductible examples below:
**WP_Query**
{{{#!php
$args = array(
'post_type' => 'post',
'post__in' => [0],
);
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) :
$wp_query->the_post();
echo $post->ID;
endwhile;
endif;
}}}
`=> returns no post`
**WP_user_query**
{{{#!php
$args = array(
'role' => '',
'include' => [0],
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
if ( ! empty( $users ) ) :
foreach ( $users as $user ) :
echo $user->ID;
endforeach;
endif;
}}}
`=> returns no user`
**WP_Term_Query**
{{{#!php
$args = array(
'taxonomy' => 'category',
'include' => [0],
);
$wp_term_query = new WP_Term_query( $args );
if ( ! empty( $wp_term_query->terms ) ) :
foreach ( $wp_term_query->terms as $term ) :
echo $term->term_id;
endforeach;
endif;
}}}
`=> returns all terms`
Credits @loicblascos for the initial bug report.",audrasjb
Tickets Needing Feedback,44965,WordPress Core strips $_GET['error'] occasionally,SergeyBiryukov*,Query,,normal,normal,Future Release,defect (bug),accepted,dev-feedback,2018-09-19T13:30:20Z,2022-09-21T09:08:29Z,"I have a plugin that is an OAuth2 consumer for integrating with Stripe Connect.
I created a new custom endpoint by adding a query var, and a rewrite rule, so everything that lands on `/stripe_connect` will get dealt with by my plugin's code.
If user denies the connection request at Stripe, they are redirected back to my site with roughly the following URL params in tow:
`/stripe_connect?state=3__5e4e4d4c9df8e6948a33fdfb44f75c0f&error=access_denied&error_description=The+user+denied+your+request`
* `state` is a custom param I set that gets replayed to me
* `error` is `access_denied`, which is the standard that Stripe will do in this case, see https://stripe.com/docs/connect/oauth-reference#get-authorize-errors
* `error_description` is a human readable problem
However in `parse_request`, a variable by the name of `$error` gets set to `404` at the beginning, and as it matches the rules, if it's still 404 (ie no other error popped up, it will then unset `$_GET['error']`.
Link to code: https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp.php#L260
Which is something I'd actually need to deal with.
Currently the way to get around it is to use `$_REQUEST` instead of `$_GET`, however `$_REQUEST` also has POST variables in it, so I can't make sure that the `error` I'm getting is actually due to a query param.
I also haven't found a ticket that had this listed as a problem.
What was the reasoning for unsetting that $_GET var?
I see that they were added originally in [1570] (14 years ago), however is that still a valid reason?",javorszky
Tickets Needing Feedback,24142,Zero value for posts_per_page value in wp_query custom instance and for 'Blog pages show at most' option,SergeyBiryukov,Query,,normal,normal,Future Release,defect (bug),reviewing,dev-feedback,2013-04-20T09:04:16Z,2024-02-18T16:12:32Z,"To show no posts if the posts_per_page value is 0.
Currently for custom instances of wp_query, if the value is 0 then this is changed with the value from posts_per_page option from the database. ""get_options( 'posts_per_page' )""
For home page if we set value 0 on the settings page, in wp-admin/options-reading.php, after the saves are changed, this value is changed to 1.
I think for both cases if the posts per page value is 0 then no posts should not display.
",alexvorn2
Tickets Needing Feedback,37762,cache_results parameter doesn't prevent queried posts from being added to cache,boonebgorges,Query,4.6,normal,normal,Future Release,defect (bug),assigned,dev-feedback,2016-08-22T09:39:42Z,2022-06-15T13:23:14Z,"Even when `cache_results` is set to `false`, the queried posts in `WP_Query` are still mapped to `get_post()` which will always add post instance to cache.
For more info: http://wordpress.stackexchange.com/questions/236653/how-to-prevent-queried-posts-from-being-added-to-cache/236659.
",Dang Vu
Tickets Needing Feedback,20899,is_home() should be able to be true when is_feed(),,Query,,normal,normal,Future Release,defect (bug),reviewing,dev-feedback,2012-06-10T19:28:36Z,2017-05-19T15:04:27Z,"is_feed() is a special query flag that can be combined with other query flags — for example, `is_author() && is_feed()` for /author/admin/feed/.
But it can't be combined with is_home(), because is_home() is the fallback that is only set to true when a lot of other things are true — including is_feed(). This appears to be incorrect — is_home() should still be able to be true despite is_feed().
I tracked this down to [1449]. What kind of breakage could occur with this?",nacin
Tickets Needing Feedback,49278,Improve meta query,,Query,5.3.2,normal,normal,Future Release,enhancement,new,dev-feedback,2020-01-23T16:32:32Z,2023-01-03T20:14:48Z,"When having a couple of Meta Query statements in WP_Query the query becomes very slow. I think this is because of the way the JOINs are created.
Currently the JOINs are only done on the Post ID. The JOIN can become enormous, which means that filtering (the WHERE part) will take a lot of time.
I checked /wp-includes/class-wp-meta-query.php and posted the code between line 557 and 573 .
{{{
// JOIN clauses for NOT EXISTS have their own syntax.
if ( 'NOT EXISTS' === $meta_compare ) {
$join .= "" LEFT JOIN $this->meta_table"";
$join .= $i ? "" AS $alias"" : '';
if ( 'LIKE' === $meta_compare_key ) {
$join .= $wpdb->prepare( "" ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )"", '%' . $wpdb->esc_like( $clause['key'] ) . '%' );
} else {
$join .= $wpdb->prepare( "" ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )"", $clause['key'] );
}
// All other JOIN clauses.
} else {
$join .= "" INNER JOIN $this->meta_table"";
$join .= $i ? "" AS $alias"" : '';
$join .= "" ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )"";
}
}}}
Apparantly when using the 'NOT EXISTS' compare the 'AND $alias.meta_key' part is added to the JOIN, but when NOT using the 'NOT EXISTS' compare this part is not there.
This means that when NOT using the 'NOT EXISTS' compare the a lot of data is joined in the temporary data set. I played with this part a bit and when adding the 'AND $alias.meta_key' part to those JOINs as well it sped up my query a lot. My query went from 38 seconds to 0.01 seconds with the same results.
My 'test' code:
{{{
// JOIN clauses for NOT EXISTS have their own syntax.
if ( 'NOT EXISTS' === $meta_compare ) {
$join .= "" LEFT JOIN $this->meta_table"";
$join .= $i ? "" AS $alias"" : '';
if ( 'LIKE' === $meta_compare_key ) {
$join .= $wpdb->prepare( "" ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )"", '%' . $wpdb->esc_like( $clause['key'] ) . '%' );
} else {
$join .= $wpdb->prepare( "" ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )"", $clause['key'] );
}
// All other JOIN clauses.
} else {
$join .= "" INNER JOIN $this->meta_table"";
$join .= $i ? "" AS $alias"" : '';
$valid_compares = array(
'=',
'!=',
'>',
'>=',
'<',
'<=',
'IN',
'NOT IN',
'EXISTS',
);
if( in_array($meta_compare, $valid_compares ) && !empty($clause['key']) && 'LIKE' !== $meta_compare_key ) {
$join .= $wpdb->prepare( "" ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )"", $clause['key']);
}
else {
$join .= "" ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )"";
}
}
}}}
I'm not really sure if this works in all cases (with all compare/compare_key variations), but I think it would be good to check it out (on Github I've seen that the last improvements here have been done at least 2 years ago).
For now I 'solved' my slow query by parsing the JOIN and WHERE on the filter 'get_meta_sql' and add the 'AND' part in the JOIN.
Below the query that gets created before and after the changes.
Query before (38 seconds):
{{{
SELECT SQL_CALC_FOUND_ROWS riff19_posts.ID FROM riff19_posts INNER JOIN riff19_postmeta ON ( riff19_posts.ID = riff19_postmeta.post_id ) INNER JOIN riff19_postmeta AS mt1 ON ( riff19_posts.ID = mt1.post_id ) INNER JOIN riff19_postmeta AS mt2 ON ( riff19_posts.ID = mt2.post_id ) INNER JOIN riff19_postmeta AS mt3 ON ( riff19_posts.ID = mt3.post_id ) JOIN riff19_icl_translations wpml_translations
ON riff19_posts.ID = wpml_translations.element_id
AND wpml_translations.element_type = CONCAT('post_', riff19_posts.post_type) WHERE 1=1 AND (
( riff19_postmeta.meta_key = 'pinplugin_event_start_date' AND CAST(riff19_postmeta.meta_value AS DATE) < '2020-01-23' )
OR
(
(
( mt1.meta_key = 'pinplugin_event_start_date' AND CAST(mt1.meta_value AS DATE) = '2020-01-23' )
AND
mt2.meta_key = 'pinplugin_event_start_time'
AND
( mt3.meta_key = 'pinplugin_event_end_time' AND CAST(mt3.meta_value AS TIME) <= '17:19:19' )
)
)
) AND riff19_posts.post_type = 'event' AND (riff19_posts.post_status = 'publish' OR riff19_posts.post_status = 'acf-disabled' OR riff19_posts.post_status = 'private') AND ( ( ( wpml_translations.language_code = 'nl' OR 0 ) AND riff19_posts.post_type IN ('post','page','attachment','wp_block','location','person','news','blog','case','service','event','vacancy','whitepaper' ) ) OR riff19_posts.post_type NOT IN ('post','page','attachment','wp_block','location','person','news','blog','case','service','event','vacancy','whitepaper' ) ) GROUP BY riff19_posts.ID ORDER BY riff19_posts.menu_order, CAST(riff19_postmeta.meta_value AS DATE) DESC, CAST(mt2.meta_value AS TIME) DESC, CAST(mt3.meta_value AS TIME) DESC LIMIT 0, 12
}}}
Query after (0.0028 seconds):
{{{
SELECT SQL_CALC_FOUND_ROWS riff19_posts.ID FROM riff19_posts INNER JOIN riff19_postmeta ON ( riff19_posts.ID = riff19_postmeta.post_id AND riff19_postmeta.meta_key = 'pinplugin_event_start_date') INNER JOIN riff19_postmeta AS mt1 ON ( riff19_posts.ID = mt1.post_id AND mt1.meta_key = 'pinplugin_event_start_date') INNER JOIN riff19_postmeta AS mt2 ON ( riff19_posts.ID = mt2.post_id AND mt2.meta_key = 'pinplugin_event_start_time') INNER JOIN riff19_postmeta AS mt3 ON ( riff19_posts.ID = mt3.post_id AND mt3.meta_key = 'pinplugin_event_end_time') JOIN riff19_icl_translations wpml_translations
ON riff19_posts.ID = wpml_translations.element_id
AND wpml_translations.element_type = CONCAT('post_', riff19_posts.post_type) WHERE 1=1 AND (
( riff19_postmeta.meta_key = 'pinplugin_event_start_date' AND CAST(riff19_postmeta.meta_value AS DATE) < '2020-01-23' )
OR
(
(
( mt1.meta_key = 'pinplugin_event_start_date' AND CAST(mt1.meta_value AS DATE) = '2020-01-23' )
AND
mt2.meta_key = 'pinplugin_event_start_time'
AND
( mt3.meta_key = 'pinplugin_event_end_time' AND CAST(mt3.meta_value AS TIME) <= '17:18:05' )
)
)
) AND riff19_posts.post_type = 'event' AND (riff19_posts.post_status = 'publish' OR riff19_posts.post_status = 'acf-disabled' OR riff19_posts.post_status = 'private') AND ( ( ( wpml_translations.language_code = 'nl' OR 0 ) AND riff19_posts.post_type IN ('post','page','attachment','wp_block','location','person','news','blog','case','service','event','vacancy','whitepaper' ) ) OR riff19_posts.post_type NOT IN ('post','page','attachment','wp_block','location','person','news','blog','case','service','event','vacancy','whitepaper' ) ) GROUP BY riff19_posts.ID ORDER BY riff19_posts.menu_order, CAST(riff19_postmeta.meta_value AS DATE) DESC, CAST(mt2.meta_value AS TIME) DESC, CAST(mt3.meta_value AS TIME) DESC LIMIT 0, 12
}}}",jillebehm
Tickets Needing Feedback,57211,Split up `WP_Query::get_posts()`,costdev,Query,,normal,normal,Future Release,enhancement,assigned,dev-feedback,2022-11-26T15:37:55Z,2023-01-23T07:15:50Z,"[https://developer.wordpress.org/reference/classes/wp_query/get_posts/#source WP_Query::get_posts()] is a huge method at ~1650 lines. This makes it quite hard to follow and maintain.
By splitting it up:
- It's easier to follow.
- It's easier to maintain.
- It's easier to write tests.
- Our scroll wheels will last a little longer.
As this is possibly the most critical method in Core, the aim of this ticket is not to refactor the logic, but just to abstract functionality. Changes to logic and such could be done later, in more maintainable code.
This should significantly reduce the chance of introducing regressions, and hopefully mean that committing such a change can be done in the near future. All new methods should have `private` visibility.",costdev
Tickets Needing Feedback,41819,Support the paged argument in WP_Site_Query and WP_Network_Query,spacedmonkey,Query,4.6,normal,normal,Future Release,enhancement,assigned,dev-feedback,2017-09-06T18:21:04Z,2017-11-01T17:47:07Z,"The {{{WP_Site_Query}}} and {{{WP_Network_Query}}} both support the {{{offset}}} and {{{number}}} arguments.
It would be handy to be able to use the {{{paged}}} argument, to make the pagination easier.
",birgire
Tickets Needing Feedback,42883,Use sargable queries for date-based lookups for posts,,Query,3.7,normal,normal,Future Release,enhancement,new,dev-feedback,2017-12-12T16:17:14Z,2022-06-14T11:57:10Z,"Related to #41054 but a very specific and actionable, high-impact instance is the fact that the WordPress lookup for permalinks involving dates is not sargable.
For a bog-standard permalink structure %year%/%slug%/, WP generates the following query:
{{{
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND ( YEAR( wp_posts.post_date ) = 2017 )
AND wp_posts.post_name = 'tahoma-vs-verdana'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
}}}
This runs (as a cold query) in ~0.075 seconds on a dedicated (and overpowered) MariaDB 10 instance on a pretty small WordPress DB. While indexes exist for all the fields matched against in the query, the use of {{{AND ( YEAR( wp_posts.post_date ) = 2017 )}}} cannot be matched against the database because MySQL/MariaDB is not intelligent enough to optimize that constraint.
The ""same"" query adjusted to make the match against {{{post_date}}} sargable does the same in ~0.034 seconds (half the time):
{{{
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_date >= DATE(""2017-01-01"")
AND wp_posts.post_date < DATE(""2018-01-01"")
AND wp_posts.post_name = 'tahoma-vs-verdana'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
}}}
The same would apply for permalinks that reference the month and day, of course.",ComputerGuru
Tickets Needing Feedback,18035,ignore_sticky_posts fails to remove sticky class,johneckman,Query,3.2,normal,normal,Future Release,enhancement,reopened,dev-feedback,2011-07-08T10:03:44Z,2023-09-20T03:13:41Z,"When setting the query_posts parameter:
ignore_sticky_posts = 1
all sticky posts are returned as normal posts and placed accordingly in the flow. However the sticky posts keep their sticky class, which means that an additional filtering of post_class is necessary to avoid any css rules defined for the .sticky selector taking effect.
is this intended, or could it be considered an enhancement if it was patched?
",mikkelbreum
Tickets with Patches,35913,`is_()` conditional methods should share their logic,,Query,,normal,normal,Future Release,defect (bug),new,dev-feedback,2016-02-23T02:54:55Z,2017-02-06T08:52:07Z,"Many of the `is_()` methods in `WP_Query` share the nearly the exact same logic. As such, they share the exact same bugs, and fixing those bugs requires many parallel changes and huge numbers of tests. See #35902 and #24674 for some recent examples.
It's possible to move all the shared logic to a single `protected` utility method. It's a bit more abstract, but is much easier to maintain and test.",boonebgorges
Tickets with Patches,56689,Use WP_Query in get_page_by_path,spacedmonkey,Query,,normal,normal,Future Release,enhancement,reopened,dev-feedback,2022-09-29T10:35:58Z,2023-02-07T04:15:36Z,"Use `WP_Query` in `get_page_by_path`, this this correctly primes caches and is cached itself. ",spacedmonkey
Tickets with Patches,36652,Use meta_value in a meta query to decide type format in SQL clause,ericlewis,Query,,normal,normal,,enhancement,reviewing,dev-feedback,2016-04-23T19:27:08Z,2019-06-04T20:57:29Z,"The SQL clause generated for a meta query [https://github.com/WordPress/WordPress/blob/4.5/wp-includes/class-wp-meta-query.php#L628 quotes the `meta_value` in a string].
This means that if there's a post with a postmeta field for likes set to 2 and you run the query looking for posts with 10 or more likes
{{{
#!php
array(
array(
'key' => 'likes',
'value' => 10,
'compare' => '>='
)
)
) );
}}}
the query will return the post with 2 likes. This is because the SQL is doing a string comparison, as both the column value and the compared-to value are strings.
The fix for the developer is to supply a `type` parameter like `NUMERIC` in the meta query clause which coerces a numeric MySQL comparison.
We could use the meta_value's type to decide the type format the value takes in the SQL clause, so that a query like this works as expected without the `type` parameter.
This was [https://core.trac.wordpress.org/ticket/27272#comment:13 suggested] by @boone in #27272.",ericlewis
Unpatched Enhancements,44658,Support BETWEEN for term names in WP_Tax_Query/WP_Term_Query,,Query,,normal,normal,Future Release,feature request,new,dev-feedback,2018-07-27T20:23:30Z,2019-09-11T15:56:51Z,This patch adds `name__between` parameter in `WP_Term_Query` and `between` operator in `WP_Tax_Query`.,soulseekah
Unpatched Bugs,55207,WP_Query returns published sticky posts when post_status is set to draft,,Query,,normal,normal,Future Release,defect (bug),new,early,2022-02-20T14:06:52Z,2022-03-28T05:37:33Z,"Originally reported here - [https://github.com/wp-cli/entity-command/issues/278]
**Error:**
If a sticky post is published, the following query returns the published sticky post:
{{{
'draft',
) );
?>
?>
}}}
Steps to reproduce:
1. Create a sticky post and publish it
2. Create a WP_Query with its 'post_status' set to 'draft'
3. Run the query
4. Observe that the published sticky post is returned
**Expected behaviour:**
Setting `post_status` to `draft` should not return published sticky posts.
",NomNom99
Slated for Next Release,59514,Add more context to split_the_query filter,,Query,3.4,normal,normal,6.6,enhancement,new,has-patch,2023-10-02T11:41:06Z,2024-03-13T15:45:24Z,"Current the split_the_query filter has the current WP_Query instance as context. However to calculate the value you need the value variables.
- $old_request
- $limits
- $fields
- $q ( query arguments ).
It is worth noting that `$this->request` can be received by `WP_Query` instance and `$wpdb->posts` can be received from global $wpdb.
With this extra context, will be make the filter much more useful.
",spacedmonkey
Tickets Awaiting Review,40630,"Advanced meta compare ""like"" in WP_Query",,Query,4.7.4,normal,normal,Awaiting Review,defect (bug),new,has-patch,2017-05-02T06:28:33Z,2017-05-16T15:17:40Z,"I try get posts with LIKE compare. For example:
{{{#!php
'any',
'meta_key' => '_stock_status',
'meta_value' => 'i%st',
'meta_compare' => 'LIKE',
]
);
} );
}}}
And I have SQL Query:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND (
( wp_postmeta.meta_key = '_stock_status' AND wp_postmeta.meta_value LIKE '%i\\%st%' )
) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'product') AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
}}}
I can't get posts with meta value for example `instock` and other matched.
",sebastian.pisula
Tickets Awaiting Review,51794,An author_name query with nonexistent user returns posts with no author,,Query,,normal,normal,Awaiting Review,defect (bug),new,has-patch,2020-11-17T03:53:56Z,2020-11-17T03:53:56Z,"This was initially noticed on a production site where an author URL with a bogus author slug (e.g. http://local.wordpress.test/author/thisuserdoesnotexist/) was returning posts.
If an `author_name` query is made with gibberish (or any nonexistent author slug), the query will return results for `post_author = 0`.
{{{
wp> $q = new WP_Query( [ 'author_name' => 'thisuserdoesnotexist' ] );
[...]
wp> $q->is_404;
bool(false)
wp> $q->found_posts;
int(3562)
wp> $q->request;
string(213) ""SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (wp_posts.post_author = 0) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10""
}}}
Are there a lot of sites out there with posts assigned to a 0 author? No idea, but my test site has a lot from generating posts via WP_CLI.
The issue stems from wp-includes/class-wp-query.php#L2254-L2258...
{{{
$q['author'] = get_user_by( 'slug', $q['author_name'] );
if ( $q['author'] ) {
$q['author'] = $q['author']->ID;
}
$whichauthor .= "" AND ({$wpdb->posts}.post_author = "" . absint( $q['author'] ) . ')';
}}}
...where a potentially false result from `get_user_by()` is cast to an int and used in a query.
With the included patch, this is the result of the same query:
{{{
wp> $q->is_404
bool(true)
wp> $q->found_posts
int(0)
wp> $q->request
string(250) ""SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_author NOT IN (0) AND (wp_posts.post_author = 0) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10""
}}}
The patch is a hack though, relying on another `absint()` to make our query search for posts that both are and are not by `0` :) There's probably a better way.
But, removing the hacky `$qv['author'] = $qv['author_name'];` line leaves this, which although returns a 404 to the browser, still runs the query:
{{{
wp> $q->is_404
bool(true)
wp> $q->found_posts
int(3562)
wp> $q->request
string(213) ""SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (wp_posts.post_author = 0) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10""
}}}",trepmal
Tickets Awaiting Review,37645,Changes made to certain is_*() functions generates PHP Notices when arrays or objects are present,,Query,4.5,normal,normal,Awaiting Review,defect (bug),new,has-patch,2016-08-12T16:12:38Z,2021-07-23T10:35:28Z,"The patch added by #35902 can generate PHP Array to string conversion notices if an array is passed that contains sub-arrays or objects that don't implement `__toString()`.
The supplied patch applies the `strval` conversion taking those special conditions into account.
Functions affected:
is_attachment()
is_author()
is_category()
is_tag()
is_page()
is_single()
I came across this using plugin I built which adds custom data, in the form of an array, to the WP_Post object for my templates to use. When `strval` is run (by post_class() calling is_attachment()) it throws notices when it comes across the arrays.",Enchiridion
Tickets Awaiting Review,52094,Queries with perm readable/editable will not work for multiple post types and status queries,,Query,,normal,normal,Awaiting Review,defect (bug),new,has-patch,2020-12-16T15:45:31Z,2022-06-15T13:03:10Z,"This ticket is a continuation of #48556, which fixes permission checks when querying for multiple post types.
If you make a query for multiple post types, and also specifying one or more post statuses, there will be a couple of problems in the results if your query also includes `perm=readable` or `perm=editable`.
`perm=readable` is supposed to do a check to see if the current user has permission to read the queried post statuses before adding it to the SQL statement. It works fine if you're querying for only one post type, but will fail for multiple post types.
The problem is the same we found in #48556. When multiple post types are queried, the permission checked will be `read_private_multiple_post_types`, instead of individually check for each post type's capabilities.
(The same happens for `perm=editable`, which will check for `edit_others_multiple_post_types`)
= Another problem: Custom post statuses =
When querying for multiple post types and `perm=readable`, WP_Query also will not handle custom post statuses properly.
Any custom post status will be treated as a `public` post status, ignoring how it was registered. You can see it happening here: https://github.com/WordPress/wordpress-develop/blob/master/src/wp-includes/class-wp-query.php#L2478
= Fix =
The fix should be similar to what we are doing in #48556, and I think we should work on the patch after we finish #48556.
= Reproducing =
I'm going to attach a test file that reproduces all the bugs described here.",leogermani
Tickets Awaiting Review,50598,Replace developer.w.org instead of Codex on is_main_query function message,,Query,,normal,minor,Awaiting Review,defect (bug),new,has-patch,2020-07-07T16:27:59Z,2020-07-07T16:28:39Z,Replace developer.w.org instead of Codex on is_main_query function message in {{{query.php}}} file.,man4toman
Tickets Awaiting Review,38062,SELECT DISTINCT ... ORDER BY ...,,Query,4.6,normal,normal,Awaiting Review,defect (bug),new,has-patch,2016-09-14T22:36:46Z,2019-04-09T18:51:23Z,"I'm not 100% certain of how best to change this in the code, but I've attached a patch that I believe is correct and fixes it ...
In '''./wp-includes/class-wp-query.php:2810''' (trunk), there is a query that looks like:
{{{
SELECT $found_rows $distinct {$this->db->posts}.ID
FROM {$this->db->posts} $join
WHERE 1=1 $where $groupby $orderby $limits
}}}
When run, in some cases at least, the query turns into:
{{{
SELECT SQL_CALC_FOUND_ROWS distinct wp_posts.ID
FROM wp_posts
...
ORDER BY wp_posts.post_date ...
}}}
The problem with the query is that it could potentially give unpredictable results ... the only reason it doesn't is because wp_posts.ID happens to be a Primary Key, and therefore, is already guaranteed that the post_date+ID will always be unique.
Now, I understand why the 'distinct' is used, as there are JOINs involved in the expanded query that could result in multiple rows being returned for each wp_post.ID, ie:
ID post_date
1 2016-09-01
2 2016-08-01
3 2016-07-01
4 2016-06-01
1 2016-09-01
4 2016-06-01
, but if that weren't the case, then the unpredictable results could come from a case like:
ID post_date
1 2016-09-01
2 2016-08-01
3 2016-07-01
4 2016-06-01
1 2016-05-01
4 2016-04-01
For the above query, which 1,4 date is to be used? If the first, then the order would be 1,2,3,4 ... if the second, the order would be 2,3,1,4 ...
If the query was changed to:
{{{
SELECT SQL_CALC_FOUND_ROWS distinct wp_posts.ID, wp_posts.post_date
}}}
... then the query becomes SQL compliant, and it is no longer possible to get unpredictable results, since in both my 'bad example' above, and in the case of the actually database table as defined for WordPress, the result would end up being:
1,2,3,4
I attached a patch that fixes the query in such a way that makes the query SQL Compliant and removes the potential unpredicatability of the results that right now is protected against by ensuring that the field itself is always UNIQUE in the first place ...
",yscrappy
Tickets Awaiting Review,50873,Search query parameter causes 404 on pagename match rules,,Query,5.4.2,normal,normal,Awaiting Review,defect (bug),new,has-patch,2020-08-07T14:55:32Z,2024-02-15T06:36:19Z,"With permalinks turned on, visit a post or page. Then append `?s=test` to the url. It should look like this: `https://example.com/post-slug/?s=test`. You will probably hit the 404 page.
The expected behavior is to get to the post or page you hit, ie `https://example.com/post-slug/`
Instead, you hit a 404 page.
This is due to both the search query and post slug query getting combined instead of one taking priority over the other.
The resulting query is a combination of a search query and post slug query which results in no posts being found, unless the search term is also in the post slug. See below:
{{{
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_name = 'post-slug'
AND (((wp_posts.post_title LIKE '%test%')
OR (wp_posts.post_excerpt LIKE '%test%')
OR (wp_posts.post_content LIKE '%test%')))
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_title LIKE '%test%' DESC, wp_posts.post_date DESC
}}}
This is using `https://example.com/post-slug/?s=test` as the example url.
I would expect the search query string to be ignore unless the visitor is on the search page (front/home page by default).",MikeNGarrett
Tickets Awaiting Review,41745,Uncaught Error in get_query_var when $wp_query is null,,Query,4.8.1,normal,normal,Awaiting Review,defect (bug),new,has-patch,2017-08-28T16:24:01Z,2021-10-01T22:58:19Z,When `get_query_var()` is called without the global $wp_query being set an Uncaught Exception is thrown.,kbjohnson90
Tickets Awaiting Review,59826,WP breaks in PHP 8.0 when passing multiple terms of same hiearchichal taxonomy to the query via GET params.,,Query,6.3.3,normal,normal,Awaiting Review,defect (bug),new,has-patch,2023-11-07T14:17:35Z,2024-01-23T21:03:20Z,"Using WC product_cat as an example here:
/shop?product_cat%5B%5D=bralettes&product_cat%5B%5D=slips
This breaks the matrix. In class-wp-query.php we find (LN 1178 - 1180):
if ( ! empty( $t->rewrite['hierarchical'] ) ) {
$q[ $t->query_var ] = wp_basename( $q[ $t->query_var ] );
}
Because ""$q[ $t->query_var ]"" is an array holding both terms, not just a string.
My patch: The if query should be changed to avoid running wp_basename on arrays:
if ( ! empty( $t->rewrite['hierarchical'] ) && ! is_array( $q[ $t->query_var ] ) ) {
$q[ $t->query_var ] = wp_basename( $q[ $t->query_var ] );
}
All the best, LXT",lxt
Tickets Awaiting Review,41224,"WP strips query vars if post contains ""wp-admin""",,Query,4.9,normal,normal,Awaiting Review,defect (bug),new,has-patch,2017-07-03T00:09:50Z,2017-07-03T10:48:55Z,"I'm running up against this rather obscure issue in the WP Query parser.
If a post name contains ""wp-admin"", the query vars are emptied which results in loading the front page instead of the post.
Repro steps:
- Use built-in PHP web server to start a WP site.
- Create a post or CPT called ""test-wp-admin""
- View the post, you will be redirected to the frontpage.
Here is the relevant code from class-wp.php
{{{
if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
unset( $perma_query_vars );
}}}
https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp.php#L276
If you inspect $_SERVER['PHP_SELF'], the resulting value is ""/index.php/test-wp-admin/"" which triggers the conditional.
It is not immediately clear to me why this is being done at all.",khromov
Tickets Awaiting Review,49284,WP_Meta_Query's 'compare_key' does not support 'NOT EXISTS' when used with WP_User_Query,,Query,5.3.2,normal,normal,Awaiting Review,defect (bug),new,has-patch,2020-01-24T13:30:25Z,2020-01-24T13:37:44Z,"The following snippet:
{{{#!php
'OR',
array(
'key' => 'learner_calculated_version',
'value' => '3',
'compare' => '!=',
),
array(
'key' => 'learner_calculated_version',
'compare_key' => 'NOT EXISTS',
)
);
$user_args = array(
'meta_query' => $meta_query
);
$users = get_users( $user_args );
global $wpdb;
print_r($wpdb->queries);
}
add_action('admin_init', 'test_get_users');
}}}
produces the following error:
{{{
WordPress database error: [Unknown column 'mt1.post_ID' in 'where clause']
SELECT DISTINCT wp_users.* FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND ( ( wp_usermeta.meta_key = 'learner_calculated_version' AND wp_usermeta.meta_value != '3' ) OR NOT EXISTS (SELECT 1 FROM wp_postmeta mt2 WHERE mt2.post_ID = mt1.post_ID AND mt2.meta_key = 'learner_calculated_version' LIMIT 1) ) ORDER BY user_login ASC
}}}
The issue is that in the subquery, wp_postmeta is queried instead of wp_usermeta.",gikaragia
Tickets Awaiting Review,60745,WP_Query::parse_query() does not handle invalid query arg values,,Query,,normal,normal,Awaiting Review,defect (bug),new,has-patch,2024-03-11T11:29:09Z,2024-03-11T11:31:45Z,"The code in `WP_Query::parse_query` assumes that most query arguments have the correct type. However, this doesn't seem to be the case for the following arguments:
Things that expect arrays, but the code that call them pass (unintended) invalid data types
{{{
'author__in' => 'string',
'author__not_in' => 'string',
'category__and' => 'string',
'category__in' => 'string',
'category__not_in' => 'string',
'post__in' => 'string',
'post__not_in' => 'string',
'post_name__in' => 'string',
'post_parent__in' => 'string',
'post_parent__not_in' => 'string',
'tag__and' => 'string',
'tag__in' => 'string',
'tag__not_in' => 'string',
'tag_slug__and' => 'string',
'tag_slug__in' => 'string',
}}}
Using most of the above query args in a `WP_Query::get_posts()` call result in a PHP fatal.
Things that expect scalars:
{{{
'attachment' => array(),
'author_name' => array(),
'feed' => array(),
}}}
Using any of the above query args result in a PHP fatal on a default WP installation:
{{{
alex@wayra core % cat .wp-env.json
{
""core"": null
}
}}}
http://localhost:8888/?attachment[]=admin
{{{
Fatal error: Uncaught TypeError: urlencode(): Argument #1 ($string) must be of type string, array given in /var/www/html/wp-includes/formatting.php:5683 Stack trace: #0 /var/www/html/wp-includes/formatting.php(5683): urlencode(Array) #1 /var/www/html/wp-includes/class-wp-query.php(2183): wp_basename(Array) #2 /var/www/html/wp-includes/class-wp-query.php(3824): WP_Query->get_posts() #3 /var/www/html/wp-includes/class-wp.php(696): WP_Query->query(Array) #4 /var/www/html/wp-includes/class-wp.php(816): WP->query_posts() #5 /var/www/html/wp-includes/functions.php(1336): WP->main('') #6 /var/www/html/wp-blog-header.php(16): wp() #7 /var/www/html/index.php(17): require('/var/www/html/w...') #8 {main} thrown in /var/www/html/wp-includes/formatting.php on line 5683
}}}
http://localhost:8888/?author_name[]=admin
{{{
Fatal error: Uncaught TypeError: str_contains(): Argument #1 ($haystack) must be of type string, array given in /var/www/html/wp-includes/class-wp-query.php:2358 Stack trace: #0 /var/www/html/wp-includes/class-wp-query.php(2358): str_contains(Array, '/') #1 /var/www/html/wp-includes/class-wp-query.php(3824): WP_Query->get_posts() #2 /var/www/html/wp-includes/class-wp.php(696): WP_Query->query(Array) #3 /var/www/html/wp-includes/class-wp.php(816): WP->query_posts() #4 /var/www/html/wp-includes/functions.php(1336): WP->main('') #5 /var/www/html/wp-blog-header.php(16): wp() #6 /var/www/html/index.php(17): require('/var/www/html/w...') #7 {main} thrown in /var/www/html/wp-includes/class-wp-query.php on line 2358
}}}
http://localhost:8888/?feed[]=admin
{{{
Fatal error: Uncaught TypeError: str_contains(): Argument #1 ($haystack) must be of type string, array given in /var/www/html/wp-includes/class-wp-query.php:1018 Stack trace: #0 /var/www/html/wp-includes/class-wp-query.php(1018): str_contains(Array, 'comments-') #1 /var/www/html/wp-includes/class-wp-query.php(1868): WP_Query->parse_query() #2 /var/www/html/wp-includes/class-wp-query.php(3824): WP_Query->get_posts() #3 /var/www/html/wp-includes/class-wp.php(696): WP_Query->query(Array) #4 /var/www/html/wp-includes/class-wp.php(816): WP->query_posts() #5 /var/www/html/wp-includes/functions.php(1336): WP->main('') #6 /var/www/html/wp-blog-header.php(16): wp() #7 /var/www/html/index.php(17): require('/var/www/html/w...') #8 {main} thrown in /var/www/html/wp-includes/class-wp-query.php on line 1018
}}}",xknown
Tickets Awaiting Review,41196,add _doing_it_wrong to get_query_var and prevent fatal errors,,Query,,normal,normal,Awaiting Review,defect (bug),new,has-patch,2017-06-28T20:32:21Z,2017-11-12T15:15:18Z,"The following scenario will throw a fatal error:
{{{#!php
current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
}
}}}
After:
{{{#!php
current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[array_key_first($this->posts)];
}
}
}}}
",diogovf
Tickets Awaiting Review,45894,is_home conditional tag returns incorrect value with home pagination,,Query,5.0.2,normal,normal,Awaiting Review,defect (bug),new,has-patch,2019-01-10T00:29:26Z,2019-01-10T12:23:45Z,"I create a index page with simple posts loop that paginate with 'the_posts_pagination' function, in default index 'is_home' returns true but when I navigate to page 2, 'is_home' returns true again!
The reading options is set on default values.
I check $wp_query in these 2 page, when 'is_page' is true we aren't in home.
So I add this condition and create the patch.",man4toman
Tickets Awaiting Review,49168,is_post_type_archive( $post_types = '' ) doesn't work with underscore (_),,Query,5.3.2,normal,normal,Awaiting Review,defect (bug),new,has-patch,2020-01-11T04:18:59Z,2020-01-11T05:04:34Z,"I define my custom post type slug using underscore, e.g. 'post_type'. But it always returns false when I try to check with `is_post_type_archive( 'post_type' )`. It turns out I have to use hyphen (-) instead of underscore (_), e.g. `is_post_type_archive( 'post-type' )`.
It is confusing because I defined the CPT using underscore, but the `is_post_type_archive()` doesn't accept underscore.
The issue is `is_post_type_archive()` uses `$post_type_object->name` instead of `$post_type_object->slug` to check against. For backward compatibility, should we accept both underscore (_) and hyphen (-) in the `is_post_type_archive( $post_types )`?",maurisrx
Tickets Awaiting Review,40660,the_post_navigation not excluding terms - wp 4.7.4,,Query,4.7.4,normal,normal,Awaiting Review,defect (bug),new,has-patch,2017-05-04T10:05:34Z,2020-07-28T05:59:17Z,"I'm retrieving the post navigation as so
{{{#!php
true,
'excluded_terms' => '129',
'taxonomy' => 'category'
);
the_post_navigation( $args )
}}}
I've debugged and it constructs the $where clause here as it should (properly excluding the term) https://github.com/WordPress/WordPress/blob/master/wp-includes/link-template.php#L1647
{{{
$where =
AND tt.taxonomy = 'category' AND tt.term_id IN (127) AND p.ID NOT IN ( SELECT tr.object_id FROM wp_term_relationships tr LEFT JOIN wp_term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) WHERE tt.term_id IN (129) ) AND ( p.post_status = 'publish' OR p.post_status = 'private' )
}}}
This is then replaced here https://github.com/WordPress/WordPress/blob/master/wp-includes/link-template.php#L1716 it improperly constructs the where clause so that the result is as follows
{{{
$where =
WHERE p.menu_order > '2' AND p.post_type = 'post' AND p.post_status = 'publish'
}}}
This means i cannot excluded other categories from the post navigation or specify which categories to exclude.
",Sbaxter_Quba
Tickets Awaiting Review,37463,Abstract Query Class,,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2016-07-25T20:50:02Z,2023-04-20T13:32:38Z,"All of the query classes WP_Comment_Query, WP_Network_Query, WP_Site_Query, WP_Term_Query and WP_User_Query are based on WP_Query class. For that reason they have a lot of similar methods and variables. As all the classes basically do the same thing, we can use an abstract class, so all related methods and variables are on the abstract class. If all query classes extend this abstract class, we can keep structure and consistency. It would also mean, for example, we could just add filters and actions in the abstract class and these would filter down. ",spacedmonkey
Tickets Awaiting Review,39120,Add get/set methods to remaining main query classes (comments and terms),,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2016-12-06T20:40:36Z,2018-04-07T12:08:19Z,"Interacting with the `$query_vars` property in `WP_Query` or `WP_User_Query` is handled through the `get()` and `set()` methods. It would be great if this could be a unified generic interface for WP's other main query classes, `WP_Comment_Query` and `WP_Term_Query`.
Patches attached.",Offereins
Tickets Awaiting Review,40434,Optimize SQL in Admin - In the Post/CPT List `wp-admin/edit.php` > the function get_posts(),,Query,4.7.3,normal,normal,Awaiting Review,enhancement,new,has-patch,2017-04-13T09:00:56Z,2018-01-17T20:31:06Z,"When we list a post, a page or a custom-post-type the default query is
{{{
SELECT SQL_CALC_FOUND_ROWS en_posts.ID
FROM en_posts
WHERE 1=1
AND en_posts.post_type = 'post'
AND (en_posts.post_status = 'publish'
OR en_posts.post_status = 'moderation'
OR en_posts.post_status = 'refusal'
OR en_posts.post_status = 'future'
OR en_posts.post_status = 'draft'
OR en_posts.post_status = 'pending'
OR en_posts.post_status = 'private')
ORDER BY en_posts.post_date DESC
LIMIT 0, 20
}}}
This query cause slow queries. The operation `OR` is not appropriate and not optimize.
It is better to use the operation `IN`.
I propose to change lines in the `clasw-wp-query.php` line 2348:
Today :
{{{#!php
is_singular ) {
$where .= "" AND ({$wpdb->posts}.post_status = 'publish'"";
// Add public states.
$public_states = get_post_stati( array('public' => true) );
foreach ( (array) $public_states as $state ) {
if ( 'publish' == $state ) // Publish is hard-coded above.
continue;
$where .= "" OR {$wpdb->posts}.post_status = '$state'"";
}
if ( $this->is_admin ) {
// Add protected states that should show in the admin all list.
$admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
foreach ( (array) $admin_all_states as $state ) {
$where .= "" OR {$wpdb->posts}.post_status = '$state'"";
}
}
if ( is_user_logged_in() ) {
// Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
$private_states = get_post_stati( array('private' => true) );
foreach ( (array) $private_states as $state ) {
$where .= current_user_can( $read_private_cap ) ? "" OR {$wpdb->posts}.post_status = '$state'"" : "" OR {$wpdb->posts}.post_author = $user_id AND {$wpdb->posts}.post_status = '$state'"";
}
}
$where .= ')';
}
}}}
The proposition :
{{{#!php
is_singular ) {
$where_status[] = 'publish';
// Add public states.
$public_states = get_post_stati( array('public' => true) );
foreach ( (array) $public_states as $state ) {
if ( 'publish' == $state ) // Publish is hard-coded above.
continue;
$where_status[] = $state;
}
if ( $this->is_admin ) {
// Add protected states that should show in the admin all list.
$admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
foreach ( (array) $admin_all_states as $state ) {
$where_status[] = $state;
}
}
if ( is_user_logged_in() ) {
// Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
$private_states = get_post_stati( array('private' => true) );
foreach ( (array) $private_states as $state ) {
$where_status[] = $state;
$where_post_author = current_user_can( $read_private_cap ) ? """" : "" OR {$wpdb->posts}.post_author = $user_id"";
}
}
$where .= "" AND ( {$wpdb->posts}.post_status IN ('"" . implode(""','"",$where_status) . ""')"";
$where .= $where_post_author;
$where .= ')';
}
}}}
And the result is better :
{{{
SELECT SQL_CALC_FOUND_ROWS en_posts.ID
FROM en_posts
WHERE 1=1
AND en_posts.post_type = 'post'
AND ( en_posts.post_status IN ('publish','moderation','refusal','future','draft','pending','private'))
ORDER BY en_posts.post_date DESC
LIMIT 0, 20
}}}
It would be interesting to do the same work on other parts of get_posts where the `OR` is used.",lriaudel
Tickets Awaiting Review,51811,Query inconsistency between WP_Query and WP_Term_Query,,Query,4.6,normal,normal,Awaiting Review,enhancement,new,has-patch,2020-11-18T01:25:43Z,2020-12-01T15:05:19Z,"For the sake of standardization and simplicity would it be beneficial to use 's' for searches in WP_Term_Query rather than using 'search'?
{{{
$wpquery = new WP_Query( array( 's'=>'search term' ) );
}}}
{{{
$wptermquery = new WP_Term_Query( array( 'search'=>'search term' ) );
}}}
Not entirely sure why there's a differentiation between how a search term is used in the query args. For the sake of standardization and a reduction in confused developers (like I was about 30 minutes ago) I think this is worth some consideration.",tonydjukic
Tickets Awaiting Review,52167,WP_Query: always convert `any` post type values to public values.,,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2020-12-24T01:01:27Z,2020-12-24T02:08:37Z,"Instantiating a WP_Query with each of the following parameters will return all public post types (post, pages and attachments by default):
{{{#!php
'any' ] );
new WP_Query( [ 'post_type' => [ 'any' ] ] );
/*
WHERE 1=1
AND wp_posts.post_type IN ('post', 'page', 'attachment')
AND ((wp_posts.post_status <> 'trash' AND wp_posts.post_status <> 'auto-draft'))
*/
}}}
However, manually adding another post type to an array containing `any` will result in a query searching for the post types `any` and the subsequent post types. This is the case regardless as to whether the included types are public or private.
{{{#!php
[ 'any', 'post' ] ] );
/*
WHERE 1=1
AND wp_posts.post_type IN ('any', 'post')
AND ((wp_posts.post_status <> 'trash' AND wp_posts.post_status <> 'auto-draft'))
*/
new WP_Query( [ 'post_type' => [ 'any', 'revision' ] ] );
/*
WHERE 1=1
AND wp_posts.post_type IN ('any', 'revision')
AND ((wp_posts.post_status <> 'trash' AND wp_posts.post_status <> 'auto-draft'))
*/
}}}
I am writing up some basic tests and create a pull request on GH to demonstrate the unexpected queries.",peterwilsoncc
Tickets Awaiting Review,55630,add array input to meta_query key,,Query,5.9.3,normal,normal,Awaiting Review,enhancement,new,has-patch,2022-04-27T14:55:34Z,2022-04-27T15:06:37Z,"use :
{{{
'meta_query' => array(
'relation' => 'OR',
array(
'key' => ['meta_key_1' , 'meta_key_2', 'meta_key_3'],
'value' => 23,
),
);
}}}
Instead of this :
{{{
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'meta_key_1',
'value' => 23,
),
array(
'key' => 'meta_key_2',
'value' => 23,
),
array(
'key' => 'meta_key_3',
'value' => 23,
),
);
}}}
",hossin277
Tickets Awaiting Review,43842,get_children() function enhancement.,,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2018-04-24T12:06:31Z,2019-01-16T06:50:09Z,This `get_children` function can be rewritten this way. And I think this is cleaner and better.,rnaby
Tickets Awaiting Review,41797,max_num_pages for WP_User_Query,,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2017-09-04T22:19:56Z,2017-09-05T08:13:21Z,"The {{{WP_User_Query}}} class supports pagination but doesn't have the public {{{max_num_pages}}} property, like most of the other query classes do.
This can be useful when using e.g. {{{paginate_links()}}} and also for better consistency.
",birgire
Tickets Awaiting Review,44602,meta_query to support FIND_IN_SET,,Query,,normal,normal,Awaiting Review,enhancement,new,has-patch,2018-07-18T17:22:08Z,2018-07-18T17:29:14Z,I got `FIND_IN_SET` working in meta_query. ,donjajo
Tickets with Patches,10663,Category name handling wrong function is_category,,Query,2.8.4,normal,normal,,defect (bug),new,has-patch,2009-08-20T15:40:46Z,2019-06-04T20:40:51Z,"When putting numbers in front of the category names, Wordpress uses them as basis for the function is_category which leads to problems with e.g. plugins using this function.
Example:
- 3 Categories: ""News"" (id 1), ""1st Release"" (id 2), ""2nd Release"" (id 3)
- Trying to check the category with is_category(1) works for news, but also returns true for the category ""1st Release""
- Trying to check the category with is_category(2) returns true for both, ""1st Release"" and ""2nd Release""
This behaviour is not expected. It might be interesting when you explicitely give the category numbers as names (e.g. ""1"", ""2"", ""3""). Changing the in_array function to a simple equal comparison makes everything work as expected.",Azaroth
Tickets with Patches,23862,Clean up old WP->public_query_vars and WP->private_query_vars,nacin,Query,,normal,normal,,defect (bug),reopened,has-patch,2013-03-25T19:20:07Z,2022-11-30T23:45:05Z,"There are some old non-working public_query_vars still in the WP class that should be cleaned up.
* posts - broken 10 years ago http://core.trac.wordpress.org/changeset/182/trunk/blog.header.php
* search - hasn’t done anything since wp_query was created
* calendar - don’t see support since ‘b2’
* pb - don’t see support since ‘b2’
* static - only used in determining if is_page, though it no longer works correctly, added http://core.trac.wordpress.org/changeset/1527/trunk, but functionality was partially changed the next commit
Also, since 'post_type' is now a public_query_var, it can be removed from the private_query_vars.
",prettyboymp
Tickets with Patches,39428,Die fast in get_posts if get_user_by returns false,,Query,4.7,normal,normal,Future Release,defect (bug),new,has-patch,2016-12-30T14:35:06Z,2019-03-15T00:52:08Z,"In case a username in the URL or passed to WP_Query via any other way is invalid - such a user is not in database - the code currently casts the `false` value returned from `get_user_by` to 0 via `absint` - see https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-query.php#L2126
Instead of trying to query unassigned posts (with `post_author` equal to `0`) for all invalid usernames, the query should die fast and return no posts.",david.binda
Tickets with Patches,44296,Enable double-width space works as a separator in search query,SergeyBiryukov,Query,,normal,normal,Future Release,defect (bug),reviewing,has-patch,2018-06-03T05:12:28Z,2019-04-10T18:16:43Z,"Related ticket: #43829
It has a bug in search query (search form).
It would be recognizing as one word in case of putting double-width space in search query.
So, it should be recognized as a separator like half-width space "" "".
And most important thing in this ticket, it can be a clue in order to approach CJK unified ideographs.
cf. ) [https://en.wikipedia.org/wiki/CJK_Unified_Ideographs]
",ryotsun
Tickets with Patches,38442,Error when WP_Query parses orderby array in function parse_order,,Query,4.2,normal,normal,Future Release,defect (bug),new,has-patch,2016-10-21T22:17:25Z,2019-04-02T20:03:42Z,"Example of query where I want to order by two custom fields in meta query
'''start_date_order''' and '''is_sticky'''
{{{#!php
true ,
'posts_per_page' => 4,
'post_type' => 'event',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'start_date_order',
'type' => 'UNSIGNED',
),
array(
'key' => 'is_sticky',
'type' => 'UNSIGNED',
),
),
'orderby' => array(
'start_date_order' => 'DESC',
'is_sticky' => 'ASC',
),
);
$result_query = new WP_Query( $args );
echo $result_query->request;
}}}
The wrong SQL query generated is
{{{
SELECT wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND (
wp_postmeta.meta_key = 'start_date_order'
AND mt1.meta_key = 'is_sticky'
)
AND wp_posts.post_type = 'event'
AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY CAST(wp_postmeta.meta_value AS UNSIGNED) DESC
LIMIT 0, 3
}}}
The '$primary_meta_query' var in method parse_order( $order ) is set forever with the first item of '$meta_clauses' array
see line 2336 /wp-includes/query.php
{{{#!php
id ) {
$query->set( 'orderby', 'post_title' );
$query->set( 'order', 'DESC' );
}
}
}}}
I came across the issue on two sites, I can reproduce it by installing 5.9 with no plugins enabled, adding the above code in a plugin or `functions.php`, everything works fine, then upgrading to 6.0 and visiting any admin screen causes the fatal error. Front-end is fine.",lumpysimon
Tickets with Patches,53824,Fatal error when in action pre_get_posts call *_template(),,Query,5.8,normal,normal,Future Release,defect (bug),new,has-patch,2021-07-29T12:43:52Z,2022-02-15T02:13:08Z,"code:
{{{
add_action('pre_get_posts', function($query) {
// when is on page
get_page_template();
});
}}}
breaks WP core in
""Allowed memory size of 134217728 bytes exhausted"" in wp-includes\class-wp-query.php
steps:
1. Add upper action to functions.php
2. Enter to any WP page
3. Fatal ERROR
It breaks WP in each function:
get_single_template()
get_category_template()
get_post_type_archive_template()
get_taxonomy_template()
get_archive_template()
get_home_template()
when function is fired in 'pre_get_posts' hook and this is current WP page.
",Adiasz
Tickets with Patches,27266,Front end search for attachment title cannot succeed,,Query,2.9,normal,normal,,defect (bug),new,has-patch,2014-03-03T20:58:32Z,2022-01-18T13:48:15Z,"This is somewhat related to ticket #22556 but affects all queries that use the keyword search parameter, 's'.
Typing an attachment's title into the ""front end"" search box generated this query:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND (((wp_posts.post_title LIKE '%Guatemala%')
OR (wp_posts.post_content LIKE '%Guatemala%'))
AND ((wp_posts.post_title LIKE '%IRF3%')
OR (wp_posts.post_content LIKE '%IRF3%')))
AND wp_posts.post_type IN ('post', 'page', 'attachment')
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_author = 1
AND wp_posts.post_status = 'private')
ORDER BY (CASE
WHEN wp_posts.post_title LIKE '%Guatemala IRF3%'
THEN 1
WHEN wp_posts.post_title LIKE '%Guatemala%'
AND wp_posts.post_title LIKE '%IRF3%'
THEN 2
WHEN wp_posts.post_title LIKE '%Guatemala%'
OR wp_posts.post_title LIKE '%IRF3%'
THEN 3
WHEN wp_posts.post_content LIKE '%Guatemala IRF3%'
THEN 4
ELSE 5 END), wp_posts.post_date DESC
LIMIT 0, 2
}}}
Although the `post_type` clause includes `attachment`, the `post_status` test always fails because attachments have a `post_status` of `inherit`.",dglingren
Tickets with Patches,37489,"If Posts have the same datetime, the order of the post is indefinite.",,Query,,normal,normal,,defect (bug),new,has-patch,2016-07-27T16:52:11Z,2019-06-04T21:02:16Z,"Posts has same datetime, the order is different, when logged in or otherwise.
",Toro_Unit
Tickets with Patches,59516,Improve cache key generation in query classes,thekt12,Query,,normal,normal,Future Release,defect (bug),assigned,has-patch,2023-10-02T13:35:14Z,2023-10-24T14:24:29Z,"In query classes such as WP_Query, parameters like post_type enable the passing of an array of values. For instance, you can use post_type like this: ['post', 'page']. However, if a subsequent request is made with the array elements in a different order, like so: ['page', 'post'], it would lead to the generation of a different cache key, potentially causing the existing cache to be missed. Even though the cached results may be the same, this could result in a cache collision. It is advisable to reuse caches whenever possible to optimize performance.
This would effect the following cache keys.
- WP_Query
- WP_Term_Query
- WP_Network_Query
- WP_Site_Query
- WP_Comment_Query
Some sort of array sorting of the key values would mean that caches could be reused. ",spacedmonkey
Tickets with Patches,52337,Non-numeric attachment_id and p query string params result in posts page,,Query,,normal,normal,Future Release,defect (bug),new,has-patch,2021-01-21T12:16:54Z,2023-10-17T18:53:40Z,"We've had a very thorough security review done on our site and the reviewer flagged up that giving a non-numeric parameter to p or attachment_id parameters: e.g.
site.com/?p=c or
site.com/?attachment_id=c
returns the posts page of the site. I would expect the 404 page. This behaviour returns the posts page even when we don't want this page to be visible on the site i.e. when the front page is set to a static page and we show the posts in other ways.
I have tested it on a clean install of the latest version of WP with no plugins.",timbarkerse
Tickets with Patches,38283,Some `WP_Query` query vars undocumented,,Query,,normal,normal,Future Release,defect (bug),new,has-patch,2016-10-11T15:07:18Z,2019-03-27T15:20:20Z,"While working on #38276, I noticed that the `has_password` and `post_password` query args (added in [27395]) aren't included in the inline docs for `WP_Query::parse_query()` with the other args. I did a search for all of the args used in `WP_Query`, and discovered that the following args are used but not documented:
{{{
attachment
caller_get_posts
embed
error
feed
has_password
minute
post_password
posts_per_rss
preview
robots
search_orderby_title
search_terms
search_terms_count
showposts
static
subpost
subpost_id
taxonomy
tb
term
term_id
withcomments
withoutcomments
}}}
Some of these may be deprecated, discouraged, or internal. If there has been a previous decision not to include them for some reason, then I apologize for bringing it up. But I couldn't find any tickets relating to the password related args not being documented, so I have a feeling that some of these may have just been overlooked.
Perhaps some of these shouldn't be documented, although we could document deprecated args and that they are deprecated, rather than just leaving them out. But at least this ticket will provide us a central place where we can state why certain ones aren't going to be documented, if indeed that's the decision.",jdgrimes
Tickets with Patches,27272,WP meta queries comparing apples to oranges,,Query,3.8.1,normal,normal,,defect (bug),reopened,has-patch,2014-03-04T16:22:44Z,2019-06-04T20:45:59Z,"As seen when hooking into the `posts_selection` hook while debugging a site:
{{{
( (ts_wp_postmeta.meta_key = 'financial_max_annual' AND CAST(ts_wp_postmeta.meta_value AS SIGNED) <= '100000') )
}}}
The thing that led to that was:
{{{
$meta_query[] = array(
'key' => $meta_key,
'value' => $max_fee,
'compare' => '<=',
'type' => 'NUMERIC',
);
}}}
Can I suggest that, when we CAST, we do so on both sides?",Denis-de-Bernardy
Tickets with Patches,27282,WP_Query returns more results when there are sticky posts,,Query,,normal,normal,Future Release,defect (bug),new,has-patch,2014-03-05T17:49:13Z,2017-01-01T00:51:00Z,"When doing a WP_Query like the one below it can return more then 3 post depending if there are sticky posts and if there are returned.
{{{
$query = new WP_Query( array(
'orderby' => 'post__in',
'post__in' => $post_ids,
'posts_per_page' => 3
) );
}}}",markoheijnen
Tickets with Patches,44737,WP_Query: in searches post_status should consider exclude_from_search,SergeyBiryukov,Query,,normal,normal,Future Release,defect (bug),reviewing,has-patch,2018-08-05T22:53:44Z,2019-11-29T16:12:56Z,"When `post_status` is empty and we are running a search, this code is executed (wp-includes/class-wp-query.php:2446):
{{{#!php
// Add public states.
$public_states = get_post_stati( array( 'public' => true ) );
foreach ( (array) $public_states as $state ) {
if ( 'publish' == $state ) { // Publish is hard-coded above.
continue;
}
$where .= "" OR {$wpdb->posts}.post_status = '$state'"";
}
}}}
That way the `exclude_from_search` parameter isn't considered.
",felipeelia
Tickets with Patches,56311,Week query variable is not being sanitized correctly,audrasjb,Query,,normal,normal,Future Release,defect (bug),assigned,has-patch,2022-07-30T09:44:25Z,2023-10-04T00:43:54Z,"If you add a ""w"" query variable to the URL of a WordPress website, for example ...
http://localhost/?w=1234
... the following PHP error notice is generated ...
PHP Notice: Function WP_Date_Query was called incorrectly. Invalid value 1234 for week. Expected value should be between 1 and 53. Please see Debugging in WordPress for more information. (This message was added in version 4.1.0.) in /wp-includes/functions.php on line 5831
This is because the `w` query string is not being correctly sanitized before being added to WP_Query. It should be checked that it is a number between 1 and 53 before being added to the query.
Oliver",domainsupport
Tickets with Patches,54371,Add posts_results-like filters to WP_Query when return fields are ids or id=>parent,,Query,,normal,normal,Future Release,enhancement,new,has-patch,2021-11-03T23:47:38Z,2022-04-11T01:57:43Z,"The WP_Query class offers no ability to hook into after queries that return posts as IDs or ID => Parent format.
The changes proposed here introduce new filters that offer similar capabilities to the pre-existing posts_results filter which runs in other cases.
This is similar to #41700 and #41678 but the approach is to address this by simply adding two new filters.
To review those other tickets and how they differ to this one:
* #41700 requests hooking into after all of the logic runs but before the return is made.
* #41678 requests refactoring the queries so that the individual ids / id=>parent queries can take advantage of all of the other hooks further down the line.
* The suggestion in this ticket is to hook the same exact way that the existing posts_results filter does without refactoring or introducing new filter naming.",sc0ttkclark
Tickets with Patches,41266,Not hard coding the table alias prefix in WP_Meta_Query would make class more extendable,noisysocks,Query,4.8,normal,normal,Future Release,enhancement,assigned,has-patch,2017-07-07T13:36:44Z,2021-11-07T19:58:01Z,"Hi,
I am extending the WP_Meta_Query class for my own uses with custom tables that have the same structure as meta tables. It is an incredibly useful class for this. However the fact that the table alias prefix {{{mt}}} on line 535 is hard coded forces me to do awkward and complex string replaces if I want to use my extensions alongside built in meta queries.
I think changing the prefix from being hard coded to a property/function of the meta query object would make this class much more versatile for plugin developers.
",thomaslhotta
Tickets with Patches,30994,Offset return for wp_get_archives,,Query,4.2,normal,normal,,enhancement,new,has-patch,2015-01-12T18:58:28Z,2019-06-04T20:48:34Z,"Adding offset to wp_get_archives is simple and can add a helpful feature.
Just as the 'limit' paramater allows results to be set to the first 10, for example, the offset parameter could allow the results to be set to 10-20, or from 15 and up.
I have some working code that I will submit as a patch.
",jefflange
Tickets with Patches,16706,"Queries using ""category__and"" are slow on large databases",chriscct7,Query,3.1,normal,normal,,enhancement,assigned,has-patch,2011-02-28T22:20:52Z,2019-06-04T20:41:52Z,"Summary: Using ""category!__and"" in query_posts() generates a dependent subquery in MySQL with extremely poor performance (""Using temporary, Using filesort"") when one of the categories has a large number of posts. The result is so slow that WordPress appears to completely hang. Changing the query structure avoids the filesort and solves it.
Details:
We have a customer doing this as part of a theme in WordPress 3.1:
{{{
query_posts(array(
""category__and"" => array(1, 461),
""posts_per_page"" => 6
));
}}}
The database is fairly large. There are 45,610 posts in category 1, and 167 posts in category 461. The resulting database query runs for so long that it effectively hangs (it doesn't finish within 30 minutes).
The generated MySQL query looks like:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND ( wp_posts.ID IN (
SELECT object_id
FROM wp_term_relationships
WHERE term_taxonomy_id IN (1,461)
GROUP BY object_id HAVING COUNT(object_id) = 2
) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 6;
}}}
An ""explain"" on this query shows that it generates a dependent subquery that devolves to a filesort:
{{{
+----+--------------------+-----------------------+-------+------------------+------------------+---------+-------------+-------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-----------------------+-------+------------------+------------------+---------+-------------+-------+-----------------------------------------------------------+
| 1 | PRIMARY | wp_posts | ref | type_status_date | type_status_date | 44 | const,const | 8177 | Using where; Using index |
| 2 | DEPENDENT SUBQUERY | wp_term_relationships | range | term_taxonomy_id | term_taxonomy_id | 8 | NULL | 25665 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+-----------------------+-------+------------------+------------------+---------+-------------+-------+-----------------------------------------------------------+
}}}
I've tried adding indexes, optimizing, and so on to get the filesort to go away, but I can't get it to do so, at least not with MySQL 5.0.x.
The filesort comes from the ""GROUP BY ... HAVING"". Changing the query to avoid those fixes this. For example, this appears to produce the same results:
{{{
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND
(
SELECT COUNT(1)
FROM wp_term_relationships
WHERE term_taxonomy_id IN (1,461)
AND object_id = wp_posts.ID
) = 2
AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 6;
}}}
But it finishes in a fraction of a second and generates cleaner ""explain"" output with no filesort:
{{{
+----+--------------------+-----------------------+------+--------------------------+------------------+---------+----------------------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-----------------------+------+--------------------------+------------------+---------+----------------------+------+--------------------------+
| 1 | PRIMARY | wp_posts | ref | type_status_date | type_status_date | 44 | const,const | 8177 | Using where |
| 2 | DEPENDENT SUBQUERY | wp_term_relationships | ref | PRIMARY,term_taxonomy_id | PRIMARY | 8 | database.wp_posts.ID | 1 | Using where; Using index |
+----+--------------------+-----------------------+------+--------------------------+------------------+---------+----------------------+------+--------------------------+
}}}
So my suggestion is that the ""category!__and"" query be changed to something like this that avoids filesorts. (I could provide a patch if people agree that this change is a reasonable approach.)",tigertech
Tickets with Patches,29424,Query argument 'orderby' makes duplicated parameters possible; does not support some available columns,johnbillion,Query,2.5,normal,normal,Future Release,enhancement,reviewing,has-patch,2014-08-29T10:22:06Z,2020-02-05T01:06:12Z,"In your newest post in [http://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/ make-blog] there a serveral errors in code.
1. Duplicated parameters are possible. Following Code will output the ""error"":
{{{
$query = new WP_Query( array( 'orderby' => array( 'title' => 'DESC', 'post_title' => 'ASC' ) ) );
//ouputs: ORDER BY post_title DESC, post_title ASC
}}}
2. Why is
* ""title"" equal to ""post_title""
* ""name"" to ""post_name""
* ""author"" to ""post_author""
and so on?
3. By the way, ""date_gmt"", ""post_status"", ""modifed_gmt"", ""content_filtered"", ""mime_type"", ""type"" are missing...
4. there are some columns missing in ""orderby"".",ChriCo
Tickets with Patches,9978,Sticky Posts are not ordered correctly after selection,,Query,2.8,normal,normal,,enhancement,assigned,has-patch,2009-05-29T23:14:06Z,2019-06-04T20:40:44Z,"In WP_Query, sticky posts are added/moved to the top of the posts array after everything else is selected and ordered according to the query parameters.
Sticky posts are loaded as a list of post_IDs from the database, according to the order they were marked as sticky.
Sticky posts that were not originally part of the returned posts are queried and added into the collection of sticky posts separately.
None of the handling of sticky posts, or the handling of the entire post array after stickies are added, is date ordered by date/title/whatever was requested.
Stickies need to be loaded/extracted into a separate array, ordered (independently) according to the original query, then added to the top of the post array.",beaulebens
Tickets with Patches,11950,Sticky Posts are too aggressive,,Query,2.9.1,normal,normal,,enhancement,reopened,has-patch,2010-01-19T15:43:50Z,2019-06-04T20:41:04Z,"I don't think the default behavior should be to have sticky posts included every time a query_posts() is used. I realize you can set the 'caller_get_posts' argument to avoid sticky posts from being added, however having to do this everywhere becomes a burden.
What are your thoughts on having the WP class add 'include_sticky' var to the_query if it isn't already set and then not include the sticky posts by default?",prettyboymp
Tickets with Patches,34525,Use wp_parse_id_list() in the WP_Query class,,Query,4.3.1,normal,normal,,enhancement,new,has-patch,2015-10-31T11:57:36Z,2019-06-04T20:52:47Z,"We have this handy core function to clean up an array, comma- or space separated list of IDs:
{{{
function wp_parse_id_list( $list ) {
if ( !is_array($list) )
$list = preg_split('/[\s,]+/', $list);
return array_unique(array_map('absint', $list));
}
}}}
Why not use it where we can?
== Examples: ==
Instead of the following lines, in the {{{WP_Query}}} class:
{{{
$q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
$q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
$q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
$q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
$q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
$q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
}}}
we could simplify it with:
{{{
$q['category__in'] = wp_parse_id_list( $q['category__in'] );
$q['category__not_in'] = wp_parse_id_list( $q['category__not_in'] );
$q['category__and'] = wp_parse_id_list( $q['category__and'] );
$q['tag__in'] = wp_parse_id_list( $q['tag__in'] );
$q['tag__not_in'] = wp_parse_id_list( $q['tag__not_in'] );
$q['tag__and'] = wp_parse_id_list( $q['tag__and'] );
}}}
Similarly for:
{{{
$author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
$author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
}}}
we could use:
{{{
$author__not_in = implode( ',', wp_parse_id_list( $q['author__not_in'] ) );
$author__in = implode( ',', wp_parse_id_list( $q['author__in'] ) );
}}}
I will check it further and soon add the relevant patches.
",birgire
Tickets with Patches,17019,add hooks for Media Library attachment counts,SergeyBiryukov,Query,2.5,normal,normal,Future Release,enhancement,reviewing,has-patch,2011-04-02T16:48:24Z,2022-03-03T11:07:24Z,"The Media Library attachments listing and edit links can be filtered via existing WP_Query and has_cap hooks. However, corresponding attachment counts are not cleanly filterable.
The submitted ticket adds the following filters:
* function wp_count_attachments() - result filter 'count_attachments'
* WP_Media_List_Table::get_views() - query filter 'attachment_orphans_query'
* function update_gallery_tab() - query filter 'gallery_attachment_count_query'",kevinB
Tickets with Patches,27094,get_boundary_post() doesn't work for custom post types,,Query,3.8.1,normal,normal,,enhancement,new,has-patch,2014-02-11T14:59:06Z,2019-06-04T20:45:44Z,"[https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-includes/link-template.php#L1318 Here the function]
I'd suggest a very little change in order to open use of the function to CPTs:
{{{
function custom_get_boundary_post( $in_same_term = false, $excluded_terms = '', $start = true, $taxonomy = 'category', $post_type = 'post' ) {
$post = get_post();
if ( ! $post || ! is_single() || is_attachment() || ! taxonomy_exists( $taxonomy ) )
return null;
$query_args = array(
'post_type' => $post_type,
'posts_per_page' => 1,
'order' => $start ? 'ASC' : 'DESC',
);
[snip]
}}}
The order of $taxonomy and $post_type arguments isn't ideal imho, but would be absolutely backward compatible.",PioneerSkies
Tickets with Patches,14477,get_pages with child_of only works with uninterrupted hierarchies,wonderboymusic,Query,3.0,high,normal,Future Release,enhancement,reopened,has-patch,2010-07-30T19:00:50Z,2021-01-15T23:32:11Z,"I have a page X with several children and grandchildren. Some of the grandchildren have a certain meta key and value. I now want to fetch all pages under page X that have this meta key. After reading the documentation of ''get_pages'', I expected this to work with a single call of ''get_pages''.
But if I use get_pages like this:
{{{
get_pages('child_of=X&meta_key=A&meta_value=B');
}}}
it returns no pages at all (hierarchical=0 has no effect). It seems that's because ''child_of'' triggers a call of ''get_page_children'' which only returns uninterrupted hierarchies. Since the query returns only some grandchildren and no direct descendants, the function fails. IMHO, that's a bug.
",vividvisions
Tickets with Patches,14368,"make the 'orderby' argument in get_posts() accept all ""post"" fields",,Query,3.0,normal,normal,,enhancement,reopened,has-patch,2010-07-20T23:58:41Z,2022-08-01T15:09:02Z,"Right now, some post's fields were not accepted when retrieving posts (even though they were documented in codex . for example ""name"" (slug) was missing).
this patch sorts the elements in the $allow_keys array (in the same order as the db' s columns) and adds the missing ones, I added every field except the ones that were long text fields (content, excerpt, etc)
",wjm
Tickets with Patches,18897,query_posts / WP_query parameter 'offset' should play nicely with 'paged',wonderboymusic,Query,3.2.1,normal,normal,,enhancement,reopened,has-patch,2011-10-10T22:18:29Z,2019-06-04T20:42:27Z,"
Setting the offset parameter with WP_query ignores the paged parameter. Thus offset can only be used as if on page 1. This is unfortunate and seems worth fixing.
See prior #2558 ""query_posts() should support offset""",here
Unpatched Enhancements,18836,ORDER BY RAND() is slow,pbearne,Query,,normal,minor,,enhancement,assigned,has-patch,2011-10-01T16:59:04Z,2024-03-12T17:55:53Z,"WP_Query currently accepts 'orderby' => 'rand' which translates to ORDER BY RAND().
This is very slow when you have many posts, since it effectively calls RAND() for each row.
A faster way would be to call RAND() only once and put it in the LIMIT clause.
The only thing is that we have to make sure that the generated number is smaller than (total number of posts - number of posts to fetch).
So, this would require to do an extra query to calculate the total. It should still be faster than the current method.
If we want to get more than one post, we can get them in any order and then call shuffle() on the resulting array.",scribu
Tickets Needing Feedback,53450,[WP_Meta_Query] Add faster LIKE based 'STARTSWITH' and 'ENDSWITH' compare modes for value query,,Query,,normal,trivial,Future Release,enhancement,new,needs-docs,2021-06-18T15:57:59Z,2022-09-20T14:56:48Z,"Currently the ""LIKE"" compare mode for meta value compares is only usable for ''contains'' queries as it always adds wildcards around all queries {{{LIKE '%query%'}}}. This makes one use the more complex REGEXP compare mode for queries which easily could be written with {{{LIKE '%query'}}} or {{{LIKE 'query%'}}}.
As LIKE is faster than REGEXP it is preferable to use LIKE.
See: http://billauer.co.il/blog/2020/12/mysql-index-pattern-matching-performance/
In addition people don't have to use the much more complex regex. Which tends to introduce errors in my experience as most people just copy & paste but do not understand how regex really works (not meant as an offense). So REGEXP should be avoided if possible.
I would suggest naming the new compare types {{{STARTSWITH}}} and {{{ENDSWITH}}}. Also adding their {{{NON ...}}} counter parts to match up the ''LIKE'' behaviour.
**Maybe** also add an alias for ''LIKE'' named {{{CONTAINS}}} as the current naming ''LIKE'' suggests that you could pass in the wildcards yourself. Which is not the case and thus misleading. But this is just for the sake of the tickets completenes. The pull request only contains code and tests for the new modes.
As an alternative I thought about reworking the current LIKE mode to allow custom wildcard passing. But this will clearly break backward compat and thus I discarded this approach.",janthiel
Tickets Awaiting Review,42164,Conditional Tags not working when using ugly URL,,Query,4.8.2,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2017-10-10T10:23:14Z,2017-10-10T13:54:21Z,"When accessing a category archive via its pretty URL e.g.
{{{
example.com/category/whatever
}}}
the conditional tag
{{{
is_category()
}}}
returns '''true'''.
Accessing the same category archive via its ugly URL
{{{
example.com?cat=whatever
}}}
the conditional tag
{{{
is_category()
}}}
returns '''false'''.
I'm pretty sure this concerns other conditional tags too. This is not only a cosmetic flaw because it causes WP to use the wrong template. I've tested it with Twenty Seventeen and the homepage template was used in case of using an ugly URL.
Due tue the ugly URL always work independently of permalink settings this is a bug in my opinion.",petersplugins
Tickets Awaiting Review,56992,The Loop displays incorrect data for queries started with `fields => 'id=>parent'`.,,Query,3.1,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2022-11-04T01:17:36Z,2022-11-04T01:17:36Z,"Using the Loop on custom `WP_Query` objects started with `fields => 'id=>parent'` will set the global post object incorrectly. Instead of containing all data, the global post object will only contain the post's ID and parent fields. All other fields are the default value.
The following test demonstrates the issue:
{{{#!php
post->create( array( 'post_type' => 'page' ) );
$child = self::factory()->post->create( array( 'post_type' => 'page', 'post_parent' => $parent ) );
$query = new WP_Query(
array(
'fields' => 'id=>parent',
'post_type' => 'page',
'page_id' => $child,
)
);
$query->the_post();
$global_post = get_post( null, ARRAY_A );
$specific_post = get_post( $child, ARRAY_A );
$this->assertEqualSetsWithIndex( $global_post, $specific_post );
}
}}}
The cause of the error is within `WP_Query::next_post()` which assumes the `WP_Query::$posts` property contains full post objects which isn't nessesarily the cause if a sub-set of fields is requested. See the [https://core.trac.wordpress.org/browser/tags/6.0.3/src/wp-includes/class-wp-query.php?marks=3447-3449#L3447 source code].
Due to #56948 the test above will currently throw an error on trunk but it will demonstrate the problem if you check out the 6.0 branch.
I suspect this has been an issue since the fields parameter was introduced in #14777 for version 3.1 but I am unable to test that far back due to PHP versions I have available on my local config.",peterwilsoncc
Tickets Awaiting Review,44695,WP_Term_Query unexpected 'orderby' behaviour.,,Query,4.9.7,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2018-08-01T21:19:14Z,2019-08-27T18:33:22Z,"I expected that `orderby` would behave in a similar way with `WP_Term_Query` as it does on other `*_Query` classes but it seems that `meta_value_date` and possibly some others is unsupported. Additionally `meta_type` doesn't function as expected either.
These args:
{{{
$args = array(
'taxonomy' => 'issues',
'number' => 5,
'meta_key' => 'issue_date',
'meta_type' => 'DATE',
'orderby' => 'meta_value_date',
);
}}}
Result in this query that has disregarded both `meta_type` and `orderby` in it's generation:
{{{
SELECT DISTINCT t.*, tt.* FROM wp_terms AS t INNER JOIN wp_termmeta ON ( t.term_id = wp_termmeta.term_id ) INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('issues') AND tt.count > 0 AND ( wp_termmeta.meta_key = 'issue_date' ) ORDER BY t.name ASC LIMIT 5
}}}
Could we get similar support for same named keys in `WP_Term_Query` as we have in other queries?",williampatton
Tickets Awaiting Review,52559,When doing JOINs for meta queries the meta_key should be in the ON clause whenever possible.,,Query,,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2021-02-17T17:17:35Z,2021-04-26T07:45:57Z,"Currently when doing `JOIN`s for meta queries the meta_key is only included in the `ON` clause if the meta compare is `NOT EXISTS`. In all other cases only the `post_id` is included.
This means that the meta key is only filtered after the JOIN is done.
Case in point, a meta_query that with 5 different keys generates the following query:
{{{#!sql
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
LEFT JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
LEFT JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id )
LEFT JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id )
LEFT JOIN wp_postmeta AS mt4 ON (wp_posts.ID = mt4.post_id AND mt4.meta_key = 'events_time_frame_end' )
WHERE 1=1 AND (
( wp_postmeta.meta_key = 'events_date_till' AND wp_postmeta.meta_value >= '20210217' )
AND
(
( mt1.meta_key = 'events_date_till' AND mt1.meta_value > '20210217' )
OR
(
( mt2.meta_key = 'events_date_till' AND mt2.meta_value = '20210217' )
AND
( mt3.meta_key = 'events_time_frame_end' AND mt3.meta_value >= '14:59:19' )
)
OR
mt4.post_id IS NULL
)
) AND wp_posts.post_type = 'events' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'dp-rewrite-republish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value ASC LIMIT 0, 10;
}}}
This query takes 60 seconds on very well provisioned database with posts that each have 50 postmeta rows in a database with 50 million total postmeta rows.
In contrast the following query:
{{{#!sql
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
LEFT JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'events_date_till' )
LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id AND mt1.meta_key = 'events_date_till' )
LEFT JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id AND mt2.meta_key = 'events_date_till' )
LEFT JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id AND mt3.meta_key = 'events_time_frame_end' )
LEFT JOIN wp_postmeta AS mt4 ON (wp_posts.ID = mt4.post_id AND mt4.meta_key = 'events_time_frame_end' )
WHERE 1=1 AND (
( wp_postmeta.meta_value >= '20210217' )
AND
(
( mt1.meta_value > '20210217' )
OR
(
( mt2.meta_value = '20210217' )
AND
( mt3.meta_value >= '14:59:19' )
)
OR
mt4.post_id IS NULL
)
) AND wp_posts.post_type = 'events' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'dp-rewrite-republish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value ASC LIMIT 0, 10;
}}}
Takes 400ms and returns identical results.
I believe the cause here is that because in the first query filtering is only done after the join and each event has 50 postmeta fields MySQL is first creating a virtual table with 50^4^ ( 4 because the last JOIN does include the meta_key ) rows joined resulting in 60.000.000 total that are then filtered back down.
Adding the meta_key condition to the `ON` clause means we're only joining 1 ( or a small number in the case of the meta_key existing in multiple rows ) rows for each JOIN meaning the virtual table being created is significantly smaller thus having much better query performance.
At the very least when there is any LEFT JOIN occurring then ALL `meta_key` conditions should be moved in the `ON` clause. Although it may be simpler to always have the `meta_key` condition in the `ON` clause.",herregroen
Tickets Awaiting Review,44964,`redirect_guess_404_permalink` doesn't support array in `post_type` var,,Query,4.9,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2018-09-19T09:35:59Z,2018-10-01T12:37:02Z,"`redirect_guess_404_permalink` doesn't support array in post_type var, but other core WordPress parts support it.",viliamkopecky
Tickets Awaiting Review,56105,Call update_post_parent_caches in the_post function in WP_Query class,,Query,,normal,normal,Awaiting Review,enhancement,new,needs-unit-tests,2022-06-30T12:01:38Z,2023-04-20T12:55:57Z,"Hello Team,
In {{{the_post}}} function {{{class WP_Query}}}, {{{update_post_author_caches}}} is already in use but not {{{update_post_parent_caches}}}.
I am not sure if it is because of {{{update_post_parent_caches}}} calls the private function {{{_prime_post_caches}}} or what.",priyankkpatel
Tickets Awaiting Review,41678,Make sure all field returns use filters in WP Query,,Query,1.5,normal,normal,Awaiting Review,enhancement,new,needs-unit-tests,2017-08-20T13:01:32Z,2023-04-20T13:19:18Z,"Currently if fields is set to either `id` or `id=>parent`, it doesn't run through all the filters as these return early.",spacedmonkey
Tickets Awaiting Review,49149,Write tests for WP_Query,,Query,,normal,normal,Awaiting Review,enhancement,assigned,needs-unit-tests,2020-01-07T22:01:10Z,2020-02-20T02:32:06Z,"WP_Query is one of the most critical classes in WordPress. It holds a lot of features and complicated rules to generate the SQL queries to fetch posts from the databases.
Working on bug fixes and new features for it is very tricky because one is always afraid that any change to it could silently break things and tear the world apart.
One way to make us feel more secure when working with this class is to have better test coverage for it. Looking at the tests we currently have I found very few tests for this class.
I've created this ticket to organize and receive patches to add tests to this class.
Below I organized the WP_Query parameters we should, at first, create tests for. Once we have tests for them individually, we can think of a way to write tests that combine different parameters.
{{{
* Author params
* author
* author_name
* author__in
* author__not_in
* Category params
* cat
* category_name
* category__and
* category__in
* category__not_in
* Tag params
* tag
* tag_id
* tag__and
* tag__in
* tag__not_in
* tag_slug__and
* tag_slug__in
* Tax_query
* Meta_query
* date_query
* post_mime_type
* fields
* name
* page_id
* pagename
* post_parent
* post_parent__in
* post_parent__not_in
* post__in
* post__not_in
* post_name__in
* has_password
* post_password
* post_type
* post_status
* comment_count
* nopaging
* posts_per_page
* offset
* paged
* ignore_sticky_posts
* order and orderby paramaters
}}}
PS - what motivated me to open this ticket (and start working on these tests) was #48556 and #44737",leogermani
Candidates for Closure,58234,sanitize_title_with_dashes fatal error when query var value is an array in php 8,,Query,,normal,normal,Awaiting Review,defect (bug),new,needs-unit-tests,2023-05-02T13:38:13Z,2023-08-08T23:23:11Z,"Using latest WordPress development version 6.3-alpha-55505-src, when submitting a form with field values that are array, and the array key is one of WordPress query vars, that causing sanitize error for 'post_name' parameter in get_posts function.
Example to replicate:
- make sure to register custom post type E.g custom_post_type.
- submit the following form on your test WordPress website.
{{{
}}}
",mouhdev
Tickets Needing Feedback,18513,Searching with explicit post types unsets page post type,,Query,3.2.1,normal,normal,,defect (bug),new,needs-unit-tests,2011-08-24T22:13:08Z,2022-02-12T20:43:32Z,"Tested on WP 3.2.1, Twenty Eleven with no plugins, multisite.
If I explicitly limit a search query via a GET request using an array of post_type values, the post_type for page is automatically excluded.
To reproduce:
* Do a search on a WP install (perhaps through a modified search form), such that the URL is like:
http://example.com/?post_type[]=post&post_type[]=page&post_type[]=attachment&s=Test
or
http://example.com/?post_type[]=post&post_type[]=page&post_type[]=book&s=Test
That's searching for ""Test"" on post, page and attachment/book post types.
* Adding the following to a theme's functions.php:
{{{
add_filter( 'pre_get_posts', 'wpcpt_search' );
/**
*
* @param array $query
*/
function wpcpt_search( $query ) {
if ( ! $query->is_search )
return $query;
print_r( $query->query_vars );
return $query;
}
}}}
That spits out (and seemingly confirmed via the values shown in the Debug Bar plugin) the following at the beginning:
{{{
Array ( [s] => Test [post_type] => Array ( [0] => post [2] => attachment )
}}}
and only returns results for posts and attachments (or books). The fact that key 1 is missing makes me think that page was in the array at some point, but it's been unset, but I can't see where, or why, this might be done.
(When no post_type is set, giving a post_type of 'any', which in turn gives all of the non-excluded_from_search post types, then page is one of the array values, and the search results correctly include pages.)
",GaryJ
Tickets Needing Feedback,51094,WP_Query.query with invalid post_status will return all,metalandcoffee*,Query,3.9,normal,critical,Future Release,defect (bug),accepted,needs-unit-tests,2020-08-21T12:18:59Z,2022-06-14T20:01:36Z,"Hello, I noticed an issue with WooCommerce method {{{ wc_get_products }}} and dove into the issue.
The problem was {{{ wc_get_products(array('status' => 'published')); }}} would return **ALL** posts, even trashed ones because of the ""published"" status is not a valid post status.
I believe that behavior is unexpected that it should return **NO** posts.
The issue appears to be this portion of {{{WP_Query.get_posts}}} that only known post statuses are added to the query:
{{{#!php
posts}.post_status = '$status'"";
} else {
$r_status[] = ""{$wpdb->posts}.post_status = '$status'"";
}
}
}
}}}
I believe it would best if this method checks for any unrequested post status supplied in the query and either applies them to the query or produces an error. I would imagine this is a pretty major change.",carsonreinke
Tickets Needing Feedback,57416,Do not split query if requesting one post,spacedmonkey,Query,3.0,normal,normal,Future Release,enhancement,assigned,needs-unit-tests,2023-01-03T13:49:30Z,2023-11-16T12:36:42Z,"When using WP_Query and requesting posts_per_page = 1, there is little to no value in splitting the query and priming posts using _prime_post_caches. This results in one query to get the posts and another to prime it. This means two database queries when this could simply be one. ",spacedmonkey
Tickets with Patches,30184,Author page and category,,Query,3.1,normal,normal,,defect (bug),new,needs-unit-tests,2014-10-29T19:20:41Z,2019-06-04T20:47:56Z,"Got errors like next in debug.log
PHP Notice: Undefined property: stdClass::$ID in /www/test1/wp-includes/query.php on line 4074
PHP Notice: Undefined property: stdClass::$nickname in /www/test1/wp-includes/query.php on line 4076
PHP Notice: Undefined property: stdClass::$user_nicename in /www/test1/wp-includes/query.php on line 4078
In wp-includes/query.php we have the method
{{{
public function is_author( $author = '' ) {
if ( !$this->is_author )
return false;
if ( empty($author) )
return true;
$author_obj = $this->get_queried_object();
$author = (array) $author;
if ( in_array( $author_obj->ID, $author ) )
return true;
elseif ( in_array( $author_obj->nickname, $author ) )
return true;
elseif ( in_array( $author_obj->user_nicename, $author ) )
return true;
return false;
}
}}}
But if we query a author page with category param queried_object actually will be the category term object, so next patch prevent such problems
{{{
public function is_author( $author = '' ) {
if ( !$this->is_author )
return false;
if ( empty($author) )
return true;
$author_obj = $this->get_queried_object();
if ( ! is_a( $author_obj, 'WP_User' ) )
return false;
$author = (array) $author;
if ( in_array( $author_obj->ID, $author ) )
return true;
elseif ( in_array( $author_obj->nickname, $author ) )
return true;
elseif ( in_array( $author_obj->user_nicename, $author ) )
return true;
return false;
}
}}}
",dimitrov.adrian
Tickets with Patches,18408,Can't wp_reset_postdata after custom WP_Query in an admin edit page,audrasjb,Query,4.7.2,normal,normal,Future Release,defect (bug),assigned,needs-unit-tests,2011-08-15T02:38:07Z,2024-02-19T22:14:25Z,"While on an edit post page (or any post type), if you create a custom WP_Query object before the editor has been output, the post data from the custom WP_Query will fill out the edit post form, not the original content of the post that is actually trying to be edited.
I found this out when trying to create a custom metabox in the 'side' context. You can reproduce this by inserting this code into a plugin:
{{{
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
function myplugin_add_custom_box() {
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post',
'side'
);
}
function myplugin_inner_custom_box() {
global $post;
$a = new WP_Query('post_type=page');
while($a->have_posts() ) : $a->the_post();
endwhile;
wp_reset_postdata();
}
}}}
This happens because $wp_query->post is never defined in the admin load, which wp_reset_postdata relies on to reset the original post data.
I am attaching a patch that defines $wp_query->post after the $post global has been defined. ",ericlewis
Tickets with Patches,34660,Query breaks when nopaging = false and posts_per_page = -1,,Query,4.4,normal,normal,,defect (bug),new,needs-unit-tests,2015-11-11T16:06:20Z,2019-06-04T20:53:11Z,"Whenever `nopaging = false` and `posts_per_page = -1`, the SQL query breaks because the LIMIT clause is set to: `LIMIT 0, -1`
This patch ensures that `nopaging` is set to TRUE whenever `posts_per_page = -1`.",mgibbs189
Tickets with Patches,27015,WP_Query::get_queried_object() does not always work in 'pre_get_posts',,Query,3.8,normal,normal,Future Release,defect (bug),new,needs-unit-tests,2014-02-05T00:58:42Z,2021-07-10T07:37:03Z,"Related: #26627
The referenced ticket fixes the situation for categories. Inline docs indicate the method returns objects for the following query types: '''category, tag, taxonomy, posts page, single post, page, author'''.
Some of these work, some do not. This became apparent from the forums:
http://wordpress.org/support/topic/get_queried_object-no-longer-working-with-pre_get_posts-and-pretty-permalinks/
Props jeich
Test setup.
Trunk at r27067 used. (and 3.7 for regression check)
Default setup of fresh install except for the following as plugin:
* Hook 'pre_get_posts' and dump get_queried_object return if it is_main_query
* Add custom taxonomy and associate with posts
* Register CPT
Change permalink setting to complete CPT rewrite registration
Also modify the DB as follows to test various query types:
* Add a tag to the Hello World post.
* Add a custom taxonomy term to the Hello World post.
* Add a CPT post
The site was browsed through various pages using the default (none) permalink, then the month and name permalink. The result of getting a queried object was recorded:
|| ||=no permalink =||=month and name=||
||uncategorized category ||stdClass object ||stdClass object||
||tag archive ||NULL ||NULL||
||taxonomy term archive ||stdClass object ||stdClass object||
||CPT archive ||stdClass object ||stdClass object||
||single post ||NULL ||NULL||
||single CPT ||NULL ||NULL||
||page ||NULL ||WP_Post object||
||author archive ||WP_User object ||False||
||posts page ||WP_Post object ||WP_Post object||
NULLs indicate failure of `get_queried_object()`. Except for tag archive, all NULLs returned are due to regression prior to 3.7. Why the tag archive failed in 3.8 is unclear, but the proposed patch addresses this issue as well as all other NULL returns.
For those that don't know, the reason for different results with pretty permalinks enabled is different query vars are defined when rewrite rules are applied. The default no pretty permalinks does not use rewrite rules and the query vars can only be what is parsed from the request.
",bcworkz
Tickets with Patches,37530,is_front_page() is based on wrong data -> gives wrong results,,Query,4.5.3,normal,normal,Future Release,defect (bug),new,needs-unit-tests,2016-07-31T14:28:49Z,2020-01-07T20:25:04Z,"1) is_front_page() is based on the SQL query, so it always gives back false when you try to use it eg at pre_get_posts. If it has no way to figure it out if it's the front page or not, it should return null instead
2) is_front_page() in themes gives the wrong result false back when you set an static page for the front page and then modify the main query on start page to posts or any other custom post type except page. This forces you to make an additionally SQL query instead of using the main query to build a custom front page.
Both is because of this: https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/query.php#L4458 . This does not really make sense to get the front page.",TheInfinity
Tickets with Patches,15667,"wp_list_pages, if it finds no pages to display, shows random child pages instead because of a bug in get_pages()",jackreichert,Query,3.0.2,normal,minor,,defect (bug),assigned,needs-unit-tests,2010-12-03T19:12:46Z,2019-06-04T20:41:37Z,"How to reproduce:[[BR]]
- About page is published
- additionally, there is a number of parent pages[[BR]]
- these each have a number of children[[BR]]
- when calling wp_list_pages(), the ""exclude"" attr excludes all parent pages, and display only the About page.
This works as long as there is at least 1 other page published that is not in the list of excluded IDs. In this example, as soon as the About page is set to ""draft"", wp_list_pages stops working correctly.
So... with no other pages besides the excluded ones published, we do this:
1) wp_list_pages('title_li=&depth=1&exclude=3,5,7');
=> wp_list_pages SHOULD return nothing, but instead it displays all child pages of the first parent page ID in the ""exclude"" attr (here: 3).
Now we now add the ""exclude_tree"" attr just for fun:
2) wp_list_pages('title_li=&depth=1&exclude=3,5,7&exclude_tree=3,5,7');
=> should again return nothing, but instead, it displays the first-ever published child page globally (here: a child page of 5).
It looked like random behavior at first but I've been able to identify the above pattern. I'm guessing it's a failing condition somewhere in the function.",bobsoap
Tickets with Patches,36881,Improved hot-wiring of set_found_posts,,Query,,normal,normal,,enhancement,new,needs-unit-tests,2016-05-18T22:45:22Z,2019-06-04T20:59:10Z,"Currently you can filter posts_request and posts_result to hot wiring the query object add caching. However, this means that in many cases the set found posts method then never gets called. This means that found posts is un-filterable. The set found posts needs to be called after the post results filter. ",spacedmonkey
Tickets with Patches,19653,Order by meta field forces ignore of null records,,Query,,normal,normal,Future Release,enhancement,new,needs-unit-tests,2011-12-23T15:11:45Z,2019-03-29T18:34:21Z,"When doing a sort on posts with a meta value, the way the SQL is currently generated in meta.php creates a condition where records that DO NOT have the queried meta value are excluded from the results. This may or may not be the desired behaviour, but we don't give developers the choice without resorting to custom queries or manual rewrites of large swathes of the $clauses array.
The issue: the way WP_Meta_Query->get_sql() creates the join on the meta key is by setting an inner join on wp_postmeta and then adding the key test to the where clause.
I would suggest writing an outer (left) join on wp_postmeta, with the key condition in the join. This would also eliminate any potential future ambiguity if, for example, you are sorting on one meta key but filtering on another, since the key condition would be within the join clause, not the where clause:
{{{
LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'my_custom_field_name'
}}}
Related to ticket #18158 is the question of how we expose this to the developer in the query API.
{{{
'meta_key' => self::get_meta_key( 'my_custom_field_name' ),
'orderby' => 'meta_value',
'exclude_empty_meta' => false
}}}
If this gets any traction I would be happy to submit a patch.",tomauger
Tickets with Patches,35907,Permit sticky posts to affect the query in REST_REQUEST,rmccue,Query,,normal,normal,Future Release,enhancement,reopened,needs-unit-tests,2016-02-22T23:44:13Z,2017-04-23T22:19:55Z,Needed for https://github.com/WP-API/WP-API/issues/2210,danielbachhuber
Tickets with Patches,20352,Use str_getcsv() to parse search terms in WP_Query,,Query,,normal,normal,,enhancement,new,needs-unit-tests,2012-04-03T23:05:25Z,2019-06-04T20:43:04Z,"We use an [http://core.trac.wordpress.org/browser/tags/3.3.1/wp-includes/query.php#L2183 ugly regex] to split search terms like these:
{{{
term1 term2 ""exact match""
}}}
We could use str_getcsv() instead, for better readability.",scribu
Tickets with Patches,45084,WP_Term_Query multiple 'orderby' support,,Query,,normal,normal,Future Release,enhancement,new,needs-unit-tests,2018-10-11T16:15:36Z,2021-03-03T20:27:19Z,"Just like in the regular WP_Query it would be awesome if it supported multiple orderby values (array or space separated).
I'm currently busy with a patch but the I would like some feedback and help with creating unit tests.
Examples:
{{{#!php
'meta_value name',
'order' => 'ASC',
);
}}}
{{{#!php
array(
'meta_value' => 'ASC',
'name' => 'ASC',
),
);
}}}
",keraweb
Tickets with Patches,23044,adjacent_image_link() needs optimization,,Query,3.5,normal,normal,,enhancement,new,needs-unit-tests,2012-12-22T05:04:20Z,2019-06-04T20:43:34Z,"`adjacent_image_link()` is really slow and stupid. It queries for '''all''' of the images attached to that post. And then it picks the previous or next one in PHP. And there's no caching, so you'll typically get this happening '''three times''' on an attachment page, (image [linked to next], prev link, next link).
We should actually just make the query grab the ONE image we want.",markjaquith
Unpatched Bugs,51852,"""any"" value in ""post_type"" param in ""get_posts"" by default ignore attachments",,Query,,normal,normal,Future Release,defect (bug),assigned,needs-unit-tests,2020-11-23T09:45:48Z,2021-02-18T00:24:52Z,"When creating a simple call to get all posts for all post types by default to the parameters are adding `post_status` parameter with `publish` value.
{{{#!php
'any']);
}}}
To the `WP_Query` instance are supplied followed arguments:
{{{#!php
5
""category"" => 0
""orderby"" => ""date""
""order"" => ""DESC""
""include"" => []
""exclude"" => []
""meta_key"" => """"
""meta_value"" => """"
""post_type"" => ""any""
""suppress_filters"" => true
""post_status"" => ""publish""
""posts_per_page"" => 5
""ignore_sticky_posts"" => true
""no_found_rows"" => true
]
}}}
All attachment posts have `inherit` post status so by default are ignored in this query.
To actually get all post types the first function parameters should be expended by `post_status` parameter with `['publish', 'inherit']` value.
{{{#!php
'any', 'post_status' => ['publish', 'inherit']]);
}}}",dam6pl
Unpatched Bugs,39540,NOT EXISTS meta condition doesn't work if meta has NULL value.,,Query,4.7,normal,normal,Future Release,defect (bug),new,needs-unit-tests,2017-01-10T16:42:19Z,2020-07-14T05:36:51Z,"It seems problem exists since meta query class release.
Right now NOT EXISTS works only if meta doesn't exist at all, but if it has NULL value we got incorrect result. I understand that better not use NULL values with metas at all, but you allow to write NULL as meta value, so please add possibility to check it.
Just need to change string in class-wp-meta-query.php:
{{{
$sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
}}}
For example on:
{{{
$sql_chunks['where'][] = ""$alias.meta_value IS NULL"";
}}}
And both cases will be covered.
Thank you in advance.
",avahura
Unpatched Bugs,23309,Not all WP_Query::query_vars get updated during WP_Query::get_posts(),,Query,,normal,normal,,defect (bug),new,needs-unit-tests,2013-01-28T15:40:56Z,2019-06-04T20:43:47Z,"There is a lot of logic within the WP_Query::get_posts() method that fills in missing query vars with defaults and manipulates others based on the rest of the query. However, some of the final states for many of the variables aren't updated in the WP_Query::query_vars array. For example, the post type is lost as a local variable and post_status is used for building compiling mysql expressions, but never directly updated.
The result is that any plugins that want to recreate the query for another system, (ie, an external search provider) must directly copy much of the business logic that WP_Query::get_posts() has embedded in it in order to fill in for the incomplete query_var array.
",prettyboymp
Unpatched Bugs,30911,Overhaul post_status logic in WP_Query,,Query,,normal,normal,,defect (bug),new,needs-unit-tests,2015-01-05T15:24:11Z,2019-06-04T20:48:22Z,"`WP_Query` filters based on post_status in two different places:
1. When building the main SQL query (`SELECT ID FROM $wpdb->posts`...). https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/query.php#L2946 This block is responsible for parsing the 'post_status' query var, and rectifying these passed post_statuses with the 'perm' param, the logged-in user's permissions, and whether `is_admin()`. (The ability to query by 'post_status' dates from [5575].)
2. On `single` queries (`is_page()`, `is_single()`), additional filtering happens *after* the query. https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/query.php#L3511 The intended purpose of this block is to ensure that Preview works (since posts being previewed generally are not published). The current incarnation of the preview logic (ie, living in `WP_Query`) was introduced in [2523].
These two 'post_status' blocks have two different purposes and two different histories, but they interact in a number of problematic ways. Just a few of the problems:
a. Querying posts with 'fields=ids' means that the post ids are returned before the second filter block gets a chance to run. As a result, certain `WP_Query` objects (eg 'p=123&post_status=trash') can return different post IDs depending on whether you request 'fields=ids'.
b. Values passed to the post_status parameter of `WP_Query` are sometimes overridden forcibly, based on logged-in user status. In an ideal world, `WP_Query` would not make any essential reference to the logged-in user. Realistically, we can't change some of this behavior for reasons having to do with backward compatibility. But there are places where the current user logic could be reworked so that it provides defaults, which can then be overridden by the params passed to `WP_Query`. Some relevant tickets: #28568, #29167
c. Filtering out non-previewable posts after the main query has taken place means doing more SQL queries than necessary in cases where post_status=draft and `is_single()`.
d. Filtering out non-previewable posts after the main query has taken place can result in certain sorts of data leakage. See eg #30910.
e. Having two separate blocks that filter results based on post_status makes unnecessarily complicated to fix post_status bugs. See eg #30530, #22001, #23309.
My initial thought is that the second block should be removed. Preview logic should either be merged with the first block of post_status parsing logic that runs when building the main post query, or it should be moved into a separate query_var, which would then be passed when making a Preview request. In general, the challenge here is to ensure that the default post_status whitelist is properly sensitive to the permissions of the logged-in user - which sometimes means building clauses like `(post_status = 'publish' OR ( post_status = 'private' AND post_author = 123 ))`.
I've started to write some unit tests that describe the (weird and complicated) existing behavior. See #29167 [31047].",boonebgorges
Unpatched Enhancements,15249,Filtering get_search_sql for advanced queries,,Query,3.1,normal,normal,,enhancement,assigned,needs-unit-tests,2010-10-29T07:00:35Z,2019-06-04T20:41:32Z,"Currently in the code for 3.1 (trunk) there are no filters running on the new function get_search_sql which would be useful for plugins to perform more complex MySQL functionality on specific columns.
I suggest adding a filter ;)",sc0ttkclark
Unpatched Enhancements,25190,Improve name/pagename query variable mapping,,Query,,normal,normal,,enhancement,new,needs-unit-tests,2013-08-30T08:12:13Z,2019-06-04T20:44:46Z,`WP_Query` performs some mappings from custom query variables to `pagename` and `name` for custom post types. This could be improved so that `pagename` is not used for hierarchical post types when a top-level item has been requested. We could also do some mappings between `pagename` and `name` in case the incorrect query variable was used (see #16323).,duck_
Unpatched Enhancements,39447,Improvement to the get_the_posts_navigation,SergeyBiryukov,Query,,normal,normal,Future Release,enhancement,reviewing,needs-unit-tests,2017-01-03T14:36:31Z,2021-01-27T06:28:38Z,"[https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/link-template.php] Here at ''get_the_posts_navigation'' the function check global wp query('''Globals['wp_query'\]''') for displaying markup. But in many cases we may need to display the navigation for '''custom wp query''' which has unique query options(max_num_page, post_per_page). So it would be great, if we can check the our custom query's max_num_page.
Hope it make sense.
Thank you
",thirumani02
Unpatched Enhancements,33306,Only Query for author ID if user is member of blog,,Query,4.3,normal,normal,,enhancement,new,needs-unit-tests,2015-08-07T17:45:42Z,2019-06-04T20:51:04Z,"In WP_Query if a user is part of the multisite install but is not part of the current blog the query is still altered from only finding public posts to finding public posts and those that are private and from that author_id. While this never has an impact on the returned end results, not having private and author ID as a parameter lets MySQL optimize the queries and in the circumstances this has been tested on (large site, lots of posts lots of users) makes them run faster. On a site without multisite installed this will have the same behavior.",sboisvert
Candidates for Closure,52732,'get_posts' has been waiting for so long to have a hook,,Query,,normal,normal,Awaiting Review,defect (bug),new,reporter-feedback,2021-03-07T20:49:37Z,2024-02-13T15:33:33Z,"I reckon `get_posts` is the most (frequently) used function across many plugins or scripts. I know there are internal `WP_Query` hooks available, but that makes things harder to get into.
I think having hook on `get_posts` will be very useful and easy for people / developers to remind & amend things easier.
patch attached.",ttodua
Candidates for Closure,59235,AJAX request returns critical error in class-wp-date-query.php,,Query,4.1,normal,normal,Awaiting Review,defect (bug),new,reporter-feedback,2023-08-29T08:35:27Z,2023-10-30T21:34:07Z,"This is due to the mktime gets the $year variable as string and not int.
This is the error code given:
{{{
PHP Fatal error: Uncaught TypeError: mktime(): Argument #6 ($year) must be of type ?int, string given in /wp-includes/class-wp-date-query.php:320
}}}
The code is:
{{{#!php
'seasonal_sessions',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'mwss_session_status',
'meta_value' => 'true',
'meta_compare' => '='
) );
$selected_session = $mwss_session;
foreach( $get_sessions as $active_session ) {
$session_name = get_the_title( $active_session->ID );
echo '';
}
?>
}}}
To recap:
- In wp-admin, logged in as Admin or editor, the dropdown is populated with results
- On front end, logged in with custom user role (most basic level, almost equivalent to a subscriber), the dropdown is populated with results
- in wp-admin, logged in as custom user role, (consistent with editor caps), the dropdown is empty",tonydjukic
Candidates for Closure,57083,wp_list_authors and WP Search Users,,Query,6.1,normal,normal,Awaiting Review,defect (bug),new,reporter-feedback,2022-11-11T22:47:31Z,2022-11-16T13:24:41Z,"Apparently `wp_list_authors` is loading a deprecated WordPress class called WP Search Users, this class has now been replaced with WP Query Users but `wp_list_authors` keeps using WP Search Users.
However the case wp list authors is only accepting some parameters, neither through array or through post accepted more parameter, meaning that something like this worked:
{{{
wp_list_authors('orderby=name&order=DESC');
}}}
but something like this did not:
{{{
wp_list_authors('orderby=name&order=ASC');
}}}
or even
{{{
wp_list_authors('orderby=name&order=DESC&optioncount=1');
}}}
My original code wasn’t working because it was stated as follows:
{{{
$authors = str_replace( ', ', ' ', wp_list_authors([
'style' => 'none',
'optioncount' => 1,
'echo' => 0
]) );
echo $authors;
}}}",pabloeduardo
Candidates for Closure,48408,Introduce eagerloading of meta data,,Query,,normal,normal,Awaiting Review,enhancement,new,reporter-feedback,2019-10-23T13:49:00Z,2019-10-23T14:01:39Z,"I believe it should be possible to introduce eagerloading to postmeta/attachments.
In ""Laravel"" language you would do:
take(10)->get();
?>
Which would produce two queries: 1) for the posts table 2) for the post_meta table where post ids IN posts result.
That would produce TWO queries to fetch 10 posts and ALL of its meta data, instead of currently where it produces a lot of requests to the database.
A SO user produced a draft that illustrates how it could work, see: https://wordpress.stackexchange.com/a/225743/50042
Speed is alfaomega in these times, and I think WordPress should take it way more serious.",mattiasf
Candidates for Closure,51796,Raw post data instead of WP_Post instances,,Query,,normal,normal,Awaiting Review,enhancement,new,reporter-feedback,2020-11-17T13:00:41Z,2020-11-19T13:20:34Z,"Within WP_Query::get_posts you find:
{{{#!php
// Convert to WP_Post objects.
if ( $this->posts ) {
$this->posts = array_map( 'get_post', $this->posts );
}
}}}
This costs a lot of time when fetching a lot of posts (e.g. products, orders, etc).
It could be fasten up by fetching only the field ""ids"" but this is also bad because when we need the post_content then a ""get_post( 123 )"" would do another query.
To bypass all of this a new ""fields operator"" could be added:
{{{#!php
if ( $this->posts && $q['fields'] !== 'raw' ) {
$this->posts = array_map( 'get_post', $this->posts );
}
}}}
The SQL-Query would still fetch all data but we would prevent the data from going through the ""get_post"" stuff.
In times of Generator it is ridiculous to iterate over the same set of data multiple times. By receiving the raw data the developer can decide when to generate a WP_Post object.
Note:
filter = ""raw"" could imply ""suppress_filters"" = true because we no longer carry WP_Post objects. But it should be allowed by the developer to switch ""suppress_filters = false"" again because the stdObjects have almost the same structure as WP_Post objects. This means (in short):
{{{#!php
if ( ! isset( $q['suppress_filters'] ) ) {
$q['suppress_filters'] = ($q['filter'] === 'raw' ? true: false);
}
}}}
",screamingdev
Tickets Needing Feedback,35418,Assigned post type not appeared in category and tag archive,,Query,4.4.1,normal,normal,,defect (bug),new,reporter-feedback,2016-01-12T14:07:24Z,2019-06-04T20:54:15Z,"In case of custom post type assign to category or tag(like use register_taxonomy_for_object_type), this post type not appeared in category and tag archive.
",jim912
Tickets Needing Feedback,34934,Suppress preg_match() and urldecode() errors in WP::parse_request().,,Query,4.4,normal,normal,,defect (bug),new,reporter-feedback,2015-12-09T14:38:01Z,2019-06-04T20:53:31Z,"Error en la fila class-wp.php
207 - 208
Aqui lo arregle asi
{{{#!php
if ( @preg_match(""#^$match#"", $request_match, $matches) || @preg_match(""#^$match#"", @urldecode($request_match), $matches) ) {
}}}
",entreosos
Tickets Needing Feedback,35848,WordPress 4.4 Handling Custom Taxonomies and Tax Queries Correctly,,Query,4.4,normal,normal,,defect (bug),new,reporter-feedback,2016-02-17T05:53:20Z,2019-06-04T20:55:22Z,"As of the WordPress 4.4 release, we have seen several sites that are using custom post types and custom taxonomies that no longer respond correctly to taxonomy page requests.
E.g.
Custom Post Type 1
-- Custom Tax 1 (slug = customtax1)
-- Custom Tax 2 (slug = customtax2)
Custom Post Type 2
-- Custom Tax 3 (slug = customtax3)
-- Custom Tax 4 (slug = customtax4)
A query like this ?customtax1=term1&customtax3=term2&customtax2=term4 should result in a taxonomy query where you get posts/post types that have the respective term values associated with the post object for each of those taxonomies. Instead as of WordPress 4.4, these queries are returning the home page of the site with is_home = true (not a taxonomy template) and completely disregarding the taxonomy query.
Important notes:
1) Custom Post Type/Taxonomy plugins have been observed on these sites. It is not limited to any specific custom post type/taxonomy plugin
2) register_post_type and register_taxonomy ARE being called by these plugins via the init hook
3) Reverting to 4.3.x fixes the issue
4) Custom taxonomies in the admin and custom post types everywhere still seem to be working the same as with previous WP versions. The issue seems to be related only to the main query of front end requests.
5) Switching themes does not fix the issue
6) Migrating the register_post_type and register_taxonomy definitions to functions.php in the main theme and verifying they are run in an init hook does not fix the issue.
7) Trying to work around the issue by running pre_get_posts and applying the appropriate tax_query to the main query does not fix the issue.
8) Setting the post_type to the associated custom post type for the custom taxonomy in a ""request"" hook or ""pre_get_posts"" hook does not fix the issue, but it does shift the theme template to the custom post type's archive template (which at least rectifies the visual display problem associated with the incorrect query parsing, but it still doesn't appropriately filter the request)
9) Creating a WP_Tax_Query manually does return the desired tax_query, but this does not appear to work with $query->set in pre_get_posts either by assigning the tax_query as an array or WP_Tax_Query object (which was a hail mary test)
Any necessary information needed to debug this can be provided. But it ""appears"" to be some sort of regression or new bug associated with the new taxonomy features and that is limited to custom post types with custom taxonomies.",vrazer
Tickets Needing Feedback,30530,Enhance privacy by hiding posts of other users,,Query,,normal,normal,,enhancement,new,reporter-feedback,2014-11-27T16:32:54Z,2019-06-04T20:48:05Z,"I haven't found an entry in Trac for this, but I know that this is discussed in blogs/stackexchage/... many times: A feature to hide posts of other authors in the admin interface.
The proposed solutions mostly include a pre_get_posts or request filter. However, most comments critizise that the post counter is still wrong. Thus, another filter for wp_count_posts is needed, duplicating much of the code of wp-includes/post.php's wp_count_posts(). Moreover, the select query in the original wp_count_posts() is executed anyway, but the result is thrown away. Finally, to make caching work, a third filter for transition_post_status to clear the post counter cache is needed.
An all this just to hide the posts of other users...
There should be an easy option to achieve this provided by the Core. There could be a 'list_others_*' capability that is honoured by query.php's get_posts() and post.php's wp_count_posts(). One could argue that published posts could be seen anyway, so the capability could also be named 'list_others_protected_*' and hides/shows the posts with a post_status marked as protected (get_posts() includes all posts with these status if we are in the admin).
That would be a great feature often requested by users and greatly enhancing the CMS capabilities!",minderdl