Querying WordPress by Post Title Instead of ID
Your current implementation uses query_posts() to fetch a specific post based on an ID passed via the p parameter in the URL. While this works for direct access, it fails when you attempt to match posts by their title string. The core issue is that the WordPress SQL query requires a specific column name and operator to perform text-based matching, rather than relying on the slug or a generic search field.
To retrieve a post based on its title, you must explicitly target the post_title column in the database using the LIKE operator. This allows for partial string matches, which is often necessary because titles can contain special characters or spaces that need proper escaping.
Constructing the SQL Query
The most reliable way to fetch a post by title without relying on query_posts() (which modifies the global $wp_query object and can interfere with WordPress core functionality) is to use WP_Query with custom arguments. You cannot simply pass the title string directly; you must construct a query that targets the specific column.
Here is how you can achieve this:
if (!empty($_GET['p'])) {
$title = sanitize_text_field($_GET['p']);
// Use WP_Query for better compatibility with global state
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'orderby' => 'title',
'order' => 'ASC',
'meta_key' => '', // Ensure we aren't filtering by meta
's' => $title // This searches title/content but is less precise
);
// For a strict title match, we need to manually construct the query or use a custom argument
// However, WP_Query doesn't natively support 'post_title' in the standard args.
// We must use get_posts() or direct SQL logic via WP_Query->query().
$posts = get_posts(array(
'numberposts' => 1,
'order' => 'ASC',
'orderby' => 'title',
// Note: There is no native 'search_title' argument in older WP versions.
// You must use a custom SQL query or rely on the 's' parameter which searches title + content.
));
}
Wait, there is a nuance here. The get_posts() function does not have a built-in argument to search only by title string equality in recent WordPress versions without using the global search parameter 's'. If you use $args['s'] = $title, WordPress will search both titles and content. To get an exact match on the title column, you often need to bypass the standard arguments or use a custom SQL query.
Using WP_Query with a Custom Clause
If you require strict matching against the post_title column (e.g., finding "My Post" even if it appears in content), the most robust approach is to construct a custom SQL clause within a WP_Query. This gives you full control over which table and column are being queried.
if (!empty($_GET['p'])) {
$title = sanitize_text_field($_GET['p']);
// Define the custom SQL query targeting post_title
$query = new WP_Query(array(
'meta_key' => '',
'posts_per_page' => 1,
'order' => 'ASC',
'orderby' => 'title',
'fields' => 'ids' // Fetch only IDs first for efficiency
));
// Since standard args don't support title-only search easily,
// we often fall back to a direct SQL query wrapped in WP_Query or get_posts logic.
// Better approach: Direct SQL via wpdb is clearer for column-specific needs.
}
Actually, the cleanest solution that avoids raw SQL while maintaining safety involves using get_posts() with a custom filter or accepting that you might need to search both title and content if an exact "title-only" argument doesn't exist in your version. However, if you want to match strictly by title, here is a pattern using WP_Query with a custom where clause:
if (!empty($_GET['p'])) {
$title = sanitize_text_field($_GET['p']);
// Escape the input to prevent SQL injection
$escaped_title = esc_sql($title);
// Construct the WHERE clause manually for title matching
$where = "AND (post_title LIKE '%{$escaped_title}%' OR post_content LIKE '%{$escaped_title}%')";
$args = array(
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC',
// We cannot easily inject arbitrary SQL into WP_Query args without custom query object.
// The most direct way in modern WP is often:
);
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
's' => $title, // Searches title and content
));
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title();
the_content();
}
wp_reset_postdata();
}
}
Handling Special Characters and Security
When searching by title, you must consider how special characters are handled. If a user enters a title like Cafe's Menu, a simple string comparison might fail if the database stores it as Café's Menu. WordPress handles accents well, but direct SQL comparisons can break without proper escaping.
Always use esc_sql() when constructing your custom clauses or ensure you rely on WordPress's built-in search logic ($args['s']) which handles these edge cases internally. However, relying on $args['s'] means the search will also look inside post content, which might return results where the title isn't an exact match but the word appears in the body.
If you need strict equality (e.g., only "My Post" and not "My Post: Part 1"), you should switch to wpdb directly or use a custom filter on the posts array after fetching them by content search.
Trade-offs with query_posts() vs WP_Query
Your original code uses query_posts(). While convenient, this function modifies the global $wp_query object. In modern WordPress themes and plugins, especially those using The Loop extensively or caching mechanisms, modifying the global query can lead to unexpected behavior, such as broken breadcrumbs or incorrect "previous/next" navigation links.
Switching to WP_Query is strongly recommended. It creates a local scope for your results and doesn't interfere with the main page load query. Additionally, if you are integrating this logic into a larger application or want to move away from WordPress core dependencies, consider building a custom API endpoint using Laravel or another framework that fetches the post data directly from the database without loading the full WordPress PHP environment.
If you are maintaining a legacy site where wp-blog-header.php is required, stick with get_posts() or a direct WP_Query instance to keep your code modular and safe. Always remember that searching by title string is inherently less precise than searching by ID, so implementing fuzzy matching logic (like LIKE '%term%') is usually the expected behavior for user-facing search features.