'Filter WP category by a custom field called town, but orderby town alphabetically not working

I have archive-jobs.php and it is filtering Jobs by a category, eg 'Developer'. This works fine, but, the issue is it's not filtering the results in alphabetical order by my custom field called 'town'.

It's not really filtering them in any logical order either.

This is my code:

<?php

$args = array( 
    'posts_per_page' => -1 ,
    'post_type' => 'jobs',
    'cat' => get_category( get_query_var( 'cat' ) )->term_id,
    'meta_key'      => 'valid_until_date', //ACF date field
    'meta_query'    => array( 
        array(
        'key' => 'valid_until_date', 
        'value' => date('Y-m-d'), 
        'compare' => '>=', 
        'type' => 'DATE'
    )),
    'meta_key'          => 'town',
    'orderby'           => 'meta_value',
    'order'             => 'ASC'
);
    
$the_query = new WP_Query( $args ); 
?>

and attached is the way the field is set up within the plugin 'Custom Fields'

enter image description here



Solution 1:[1]

orderby => "metavalue" will use the metadata key at meta_key to order posts.

You have two instances of meta_key used in your query - you should remove 'meta_key' => 'valid_until_date' for it to recognize you want to order by town instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sean