WordPress Search

Search Functionality

The basic WordPress search pulls only information from the database housing the WordPress site. When a user enters their search query, WordPress scans the database to retrieve content matching the keyword(s) entered. It first displays any posts or pages containing the keyword in the title, followed by posts or pages containing the keyword in their excerpt. It then searches post content and matches any posts or pages containing the keyword in their body text. It also searches for single image titles and captions, image alt text, and file names. It does not search for the keyword in user comments, widgets, custom post types, widgets, categories, or tags, and the search results are sorted in reverse chronological order, not by relevance.

URI Role in Search

The default URI for a WordPress search uses this formatting: "website.com/?s=search-query. This makes technical sense, as the term after "?s=" contains the user's search query, formatted to remove spaces. However, this is not human-friendly or SEO-optimized. Using a plugin like WPCode allows you to format the URI to display with more helpful and readable terms, replacing "?s=" with a term like "search" to make it clearer to users what is being displayed on the page.

Display the Current/Active Search Term

To display the current or active search term, you can use a function like get_search_query() to retrieve the contents of the WordPRess query variable. The query string is sanitized using esc_attr() to ensure no HTML entities are encoded via a user's search query. Storing the value retrieved in a variable and echoing it in an HTML element on the page will display the current search term and can be used to display to the user what query was searched for. In the search form itself, it can be used to keep the search term in the textbox after the search is submitted.

Summary

When a user submits a search on a WordPress site, WordPress searches the database and matches the term with any posts or pages containing the term in their title, excerpt, or content. The search term is displayed in the URI as "?s=search-query" unless optimized to display in a more user-friendly way, such as "search/search-query." The current search term can be displayed using the function get_search_query() to retrieve the current search query and store it in a variable to be echoed anywhere on the page.