WordPress.org

Make WordPress Core

Opened 3 months ago

Last modified 2 months ago

#50873 new defect (bug)

Search query parameter causes 404 on pagename match rules

Reported by: MikeNGarrett Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 5.4.2
Component: Query Keywords: has-patch has-unit-tests
Focuses: performance Cc:

Description

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).

Attachments (1)

50873-search-query.diff (538 bytes) - added by daxelrod 3 months ago.
Checks if the request is a search query before parsing the 's' query var.

Download all attachments as: .zip

Change History (4)

@daxelrod
3 months ago

Checks if the request is a search query before parsing the 's' query var.

#2 @daxelrod
3 months ago

In discussing with @MikeNGarrett and @kshaner the 404 behavior originates from class-wp.php:handle_404() which receives a query with no posts.

Tracing backwards, in class-wp-query.php:parse_query() the is_search state should only be triggered if attachment/p/postname/pagename is not set, but class-wp-query.php:get_posts() only looks for strlen( $q['s'] ) (ignoring if it were a singular query). The logic was resulting in a query that was both selecting a post, and searching at the same time. The query (typically) selects 0 posts, which results in the 404.

This ticket was mentioned in PR #465 on WordPress/wordpress-develop by donmhico.


2 months ago

  • Keywords has-patch has-unit-tests added

This PR fixes the issue where 404 is returned when search query parameter is present and a post slug has a match. The PR uses @daxelrod's patch. I added a unit test.

Trac ticket: https://core.trac.wordpress.org/ticket/50873

Note: See TracTickets for help on using tickets.