{"id":201119,"date":"2015-05-01T12:36:28","date_gmt":"2015-05-01T19:36:28","guid":{"rendered":"http:\/\/css-tricks.com\/?p=201119"},"modified":"2022-11-15T12:26:50","modified_gmt":"2022-11-15T20:26:50","slug":"ignoring-the-in-wordpress-queries","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/ignoring-the-in-wordpress-queries\/","title":{"rendered":"Ignoring `the` in WordPress Queries"},"content":{"rendered":"\n

The following is a post by Jason Witt<\/a>. Here Jason shares a method for doing something you might assume is pretty easy, but turns out to be a little bit more complicated than you might like. Fortunately with Jason’s code and examples, it can be easy.<\/em><\/p>\n\n\n\n\n\n\n\n

Recently I had to make a custom WordPress query that listed post titles in alphabetical order. I started with a basic query like this.<\/p>\n\n\n\n

$my_query = new WP_Query(array(\n  'post_type'  => 'post',\n  'orderby'    => 'title',\n  'order'      => 'ASC'\n));<\/code><\/pre>\n\n\n\n

My results were:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

The results are technically in alphabetical order, but not how I wanted. I wanted the word “the” to be ignored if it was the title started with that, and to alphabetize by the next word instead. The desired order should look like this:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n\n

The “the” is called an Initial Article<\/em>. You know: “A”, “An”, and “The”, the thing that sometimes gets put at the beginning of proper nouns. If you want to go international you can include “La” (Spanish) and “Les” (French). After a lot of searching and combing through WordPress Codex, I couldn’t find a native WordPress WP_Query<\/code> solution for ignoring an Initial Article.<\/p>\n\n\n\n

What I did find were two very helpful filters that can let me achieve this, posts_fields<\/code> and posts_orderby<\/code><\/a>. With a little SQL know-how and PHP trickery. I was able to achieve the desired result.<\/p>\n\n\n\n

Perhaps unsurprisingly, this is a pretty common need. Imagine a music library. Grouping all the bands that start with “The” under “T” would be needlessly confusing. Instead it’s like this:<\/p>\n\n\n\n

\"\"<\/figure>\n\n\n

How To Do It<\/h3>\n\n\n

Let me share with you how I did it, so you can use this in any WordPress project that requires you to alphabetize a WordPress query while ignoring Initial Articles.<\/p>\n\n\n\n

In your `functions.php` file, add the following two functions.<\/p>\n\n\n\n

function wpcf_create_temp_column($fields) {\n  global $wpdb;\n  $matches = 'The';\n  $has_the = \" CASE \n      WHEN $wpdb->posts.post_title regexp( '^($matches)[[:space:]]' )\n        THEN trim(substr($wpdb->posts.post_title from 4)) \n      ELSE $wpdb->posts.post_title \n        END AS title2\";\n  if ($has_the) {\n    $fields .= ( preg_match( '\/^(\\s+)?,\/', $has_the ) ) ? $has_the : \", $has_the\";\n  }\n  return $fields;\n}\n\nfunction wpcf_sort_by_temp_column ($orderby) {\n  $custom_orderby = \" UPPER(title2) ASC\";\n  if ($custom_orderby) {\n    $orderby = $custom_orderby;\n  }\n  return $orderby;\n}<\/code><\/pre>\n\n\n\n

This first function, wpcf_create_temp_column<\/code>, is going to create a virtual table column named “title2” at the time of the query. It populates the table column with the titles of your posts. If the title has the Initial Article “The”, it will be removed.<\/p>\n\n\n\n

The second function, wpcf_sort_by_temp_column<\/code>, creates a new custom orderby<\/code>. It orders the posts by the virtual table column “title2” using the ASC<\/code> order.<\/p>\n\n\n\n

To have these function work their magic on your<\/em> queries, you simply add them to the filters I mentioned before.<\/p>\n\n\n\n

add_filter('posts_fields', 'wpcf_create_temp_column');\nadd_filter('posts_orderby', 'wpcf_sort_by_temp_column');<\/code><\/pre>\n\n\n\n

Now your queries will order your post titles in alphabetical order while ignoring the Initial Article “The”. If you want to add additional Initial Articles to be ignored all you have to do is include them to the $matches<\/code> variable in the wpcf_create_temp_column<\/code> function, and separate them with a pipe character.<\/p>\n\n\n\n

$matches = 'A|An|The|La|Les';<\/code><\/pre>\n\n\n\n

Now let’s say you have multiple WordPress queries that are being ordered by the title, but you don’t want to apply these filters to those queries. By adding the filters in your `functions.php` file they will affect every query on your site, so you probably don’t want that. Not to mention it may affect your site’s performance by using unnecessary filters. Here’s how you can apply those filters to specific queries.<\/p>\n\n\n\n

First remove the add_filter<\/code> functions from your `functions.php` file. Then in your template file with desired query, put the add_filter<\/code> functions along with remove_filter<\/code> functions like this.<\/p>\n\n\n\n

add_filter('posts_fields', 'wpcf_create_temp_column'); \/\/ Add the temporary column filter\nadd_filter('posts_orderby', 'wpcf_sort_by_temp_column'); \/\/ Add the custom order filter\n\n$query = new WP_Query(array('post_type' => 'post')); \/\/ Your custom query\n\nremove_filter('posts_fields','wpcf_create_temp_column'); \/\/ Remove the temporary column filter\nremove_filter('posts_orderby', 'wpcf_sort_by_temp_column'); \/\/ Remove the temporary order filter \n\nif (have_posts()) : while ($query->have_posts()) : $query->the_post(); \/\/ The query output\n\n  the_title(); \n  echo '<br\/>';\n\nendwhile; endif; wp_reset_postdata();<\/code><\/pre>\n\n\n\n

In the above code, you’re adding the filters, executing the query, and then immediately removing the filters. By wrapping the query code in the filter your isolating those filter to that specific query.<\/p>\n\n\n\n

Happy sorting!<\/p>\n","protected":false},"excerpt":{"rendered":"

The following is a post by Jason Witt. Here Jason shares a method for doing something you might assume is pretty easy, but turns out to be a little bit more complicated than you might like. Fortunately with Jason’s code and examples, it can be easy.<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"sig_custom_text":"","sig_image_type":"featured-image","sig_custom_image":0,"sig_is_disabled":false,"inline_featured_image":false,"c2c_always_allow_admin_comments":false,"footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":[]},"categories":[4],"tags":[264],"jetpack_publicize_connections":[],"acf":[],"jetpack_featured_media_url":"","jetpack-related-posts":[{"id":203594,"url":"https:\/\/css-tricks.com\/finding-and-fixing-slow-wordpress-database-queries\/","url_meta":{"origin":201119,"position":0},"title":"Finding and Fixing Slow WordPress Database Queries","date":"June 16, 2015","format":false,"excerpt":"Slow SQL queries can crush your WordPress site's performance. Sometimes, slow queries are a result of poorly-formed SQL that never should have been done that way. And sometimes, slow queries were actually fast queries at one point\u2014but as the site grew older, the query got slower and slower, unable to\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":246280,"url":"https:\/\/css-tricks.com\/declarative-data-fetching-graphql\/","url_meta":{"origin":201119,"position":1},"title":"Declarative Data Fetching with GraphQL","date":"October 13, 2016","format":false,"excerpt":"The following is a guest post by Nilan Marktanner from Graph.cool. I don't know about y'all but I've spent plenty of time in my career dealing with REST API's. It's a matter of always trying to figure out what URL to hit, what data to expect back, and how you\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":203063,"url":"https:\/\/css-tricks.com\/swapping-a-wordpress-core-meta-box-to-speed-up-editing\/","url_meta":{"origin":201119,"position":2},"title":"Swapping a WordPress core meta box to speed up editing","date":"July 8, 2015","format":false,"excerpt":"The CSS-Tricks front end is usually pretty darn fast, because most pages are cached (and don't need to be dynamically generated when requested). However, up until recently, the CSS-Tricks WordPress admin didn't have the same luck. In particular, the post editing screen was slow. Painfully slow. Saving a draft took\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":238093,"url":"https:\/\/css-tricks.com\/using-calc-to-fake-a-media-query\/","url_meta":{"origin":201119,"position":3},"title":"Using calc() to fake a media query","date":"February 17, 2016","format":false,"excerpt":"A bonafide CSS trick by R\u00e9mi Parmentier. It's used in the context of emails here, but it's a clever trick in it's own right. This is the trick: \/* When parent is 500px wide... *\/ .block { min-width: 50%; \/* 250px WINNER *\/ max-width: 100%; \/* 500px *\/ width: calc(480px\u2026","rel":"","context":"In "Link"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":293453,"url":"https:\/\/css-tricks.com\/quick-gulp-cache-busting\/","url_meta":{"origin":201119,"position":4},"title":"Quick Gulp Cache Busting","date":"August 7, 2019","format":false,"excerpt":"You should for sure be setting far-out cache headers on your assets like CSS and JavaScript (and images and fonts and whatever else). That tells the browser \"hang on to this file basically forever.\" That way, when navigating from page to page on a site \u2014 or revisiting it, or\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2019\/08\/gulp-dynamite.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":21614,"url":"https:\/\/css-tricks.com\/media-query-change-detection-in-javascript-through-css-animations\/","url_meta":{"origin":201119,"position":5},"title":"Media Query Change Detection in JavaScript Through CSS Animations","date":"May 14, 2013","format":false,"excerpt":"The following is a guest post by Alessandro Vendruscolo. Media queries are relevant to both CSS and JS. The need and desire to manage those in one place is real. There have been some clever ways to do this, like Jeremy Keith's Conditional CSS. But in that case, the onus\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/201119"}],"collection":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/comments?post=201119"}],"version-history":[{"count":4,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/201119\/revisions"}],"predecessor-version":[{"id":375330,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/201119\/revisions\/375330"}],"wp:attachment":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media?parent=201119"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/categories?post=201119"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/tags?post=201119"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}