Make sorting ignore “the” OR sort by slug
-
I need my posts to display in alphabetical order, but ignoring initial articles like “A” and “The”. I was able to implement the solution found at https://css-tricks.com/ignoring-the-in-wordpress-queries/ by adding the code (including the filters) to my functions.php child theme file.
This worked great, but also overrode a couple of plugins:
1. A related posts plugin that sorted by relevance
2. A featured posts plugin that randomized postsAccording the the CSS Tricks article, I need to move the filter calls to the specific places where I want the customized sort to happen. The problem is I’m not savvy enough to figure out where. I know enough to copy and paste code to where I’m directed to, but not enough to customize existing functions to accommodate new code.
This is the code I’m using:
function wpcf_create_temp_column($fields) { global $wpdb; $matches = 'A|An|The'; $has_the = " CASE WHEN $wpdb->posts.post_title regexp( '^($matches)<a href="https://codex.wordpress.org/:space:">:space:</a>' ) THEN trim(substr($wpdb->posts.post_title from 4)) ELSE $wpdb->posts.post_title END AS title2"; if ($has_the) { $fields .= ( preg_match( '/^(\s+)?,/', $has_the ) ) ? $has_the : ", $has_the"; } return $fields; } function wpcf_sort_by_temp_column ($orderby) { $custom_orderby = " UPPER(title2) ASC"; if ($custom_orderby) { $orderby = $custom_orderby; } return $orderby; } add_filter('posts_fields', 'wpcf_create_temp_column'); add_filter('posts_orderby', 'wpcf_sort_by_temp_column');Is there a way to make this not affect plugins?
Alternatively if there’s a way to tell WordPress to sort by slug instead of title, that would work too. It just needs to not affect those two plugins. I’ve read tons of different posts about sorting by slug, but they involve specific functions that coders are working on for their custom themes. I need something beginner-friendly that I can copy and paste. Does such a solution exist?
The page I need help with: [log in to see the link]
The topic ‘Make sorting ignore “the” OR sort by slug’ is closed to new replies.