Home Forums Front-end Issues Sort Custom Post Type Alphabetically


Sort Custom Post Type Alphabetically

  • Hi Community

    I’m trying to sort posts within my custom post type alphabetically on a custom field called ‘surname’.

    I’m following the example for functions.php here

    But its not working.

    My custom post type is

    The code in functions.php is

    function my_pre_get_posts( $query ) {
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	// only modify queries for 'ceramicist' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'ceramicist' ) {
    		$query->set('orderby', 'meta_value');	
    		$query->set('meta_key', 'surname');	 
    		$query->set('order', 'ASC'); 
    		$query->set( 'suppress_filters', 'true' );
    	// return
    	return $query;

    Am I missing something here or if this looks Ok then perhaps my bespoke theme is preventing it form running correctly.

    Thank you

  • Hmm

    Just installed a child theme on the default 2021 theme and still not alphabetically sorting.
    So appears not to be my bespoke child theme.

  • Noticed I had forgotten to add

    add_action('pre_get_posts', 'my_pre_get_posts');

    But that hasn’t helped either

  • Sorry – yes it has!


    add_action('pre_get_posts', 'my_pre_get_posts');

    fixed it.

    How embarrassing.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.