I have a page template “By Author” (ID 1814) I am using to query my posts (Title: book titles & Content: descriptions) by meta_key: author_name, which equals both the book author’s first & last name_ However, I would like to order these posts by just the author’s last name â the second word in the meta_value. I am able to filter get these results in the loop by using:
$values = get_post_custom_values("author_name");
$alpha = end(explode(' ',$values[0]));
But I don’t know how to get these posts to order by this result not by author_name’s first name. I found the query below for the functions.php file, which I think puts me on the right path but returns a 404 error on my page when I use it.
Code from here: http://randyhoyt.com/wordpress/custom-post-type-ordering/
I haven’t even added the SQL query to explode (or whatever it is in SQL not PHP). Not sure if that code isn’t working because I am querying on a page template and not an archive.php file? Any suggestions to get me on the right path?
add_filter('posts_join', 'author_join' );
function author_join($wp_join) {
if(is_page(1814)) {
global $wpdb;
$wp_join .= " LEFT JOIN (
SELECT post_id, meta_value as author_name
FROM $wpdb->postmeta
WHERE meta_key = 'author_name' ) AS DD
ON $wpdb->posts.ID = DD.post_id ";
}
return ($wp_join);
}
add_filter('posts_orderby', 'author_order' );
function author_order( $orderby ) {
if(is_page(1814)) {
$orderby = " DD.post_title ASC";
}
return $orderby;
}
I’ve dealt with a similar issue where band names starting with “The …” were alphabetically ordered at T. The fix I implemented was to reverse the order of the name in the database to satisfy the MySQL query, and then the display page can use a string function to reverse the name back to the proper order.
Something like this on the display page would fix the output: