Sort Custom Post Type by Second Word in Title
-
I have a CPT called people. Each post title includes the person’s first and last name. (First name, followed by Last Name). I’d like to display the posts in alphabetical order according to the last name.
After reading through some documentation, I added the following to my functions.php file:
function posts_orderby_lastname ($orderby_statement) { $orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) DESC"; return $orderby_statement; }
My issue now is that I’m not sure how or where to add this in my query.
Here is the code for my query to display my CPT posts:
<?php $args = array( 'post_type' => 'people', 'orderby' => 'title', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'people', 'field' => 'slug', 'terms' => 'njapf' ) ) ); //$query = new WP_Query( $args ); // this line is useless in your code // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<div class="artist-grid-item">'; if(has_post_thumbnail()){ echo '<a href="'. get_permalink() . '">'; echo '<div class="artist-grid-image">' . get_the_post_thumbnail( $_post->ID, 'large' ) . '</div>'; } echo '<p>' . get_the_title() . '</p>'; echo ' </a></div>'; } } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata();?>
How can I add the filter to my existing custom query?
The page I need help with: [log in to see the link]
Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
- The topic ‘Sort Custom Post Type by Second Word in Title’ is closed to new replies.