Sort an array by a meta_key

Looking to sort an array in an ascending order based on a numerical meta_key.

This is based on a function for the Facet WP plugin: https://facetwp.com/preserving-sticky-posts-in-templates/

Read More

As you can see, the code provided by Facet WP is as follows:

function fwp_preserve_sticky_posts( $query ) {
    if ( 'ids' == $query->get( 'fields' ) ) {
        return;
    }

    if ( isset( $query->query_vars['show_sticky'] ) ) {
        $matches = array();
        $sticky = (array) get_option( 'sticky_posts' );
        $post_in = (array) $query->query_vars['post__in'];

        foreach ( $sticky as $post_id ) {
            if ( false !== ( $pos = array_search( $post_id, $post_in ) ) ) {
                $matches[ $pos ] = $post_id;
            }
        }
        ksort( $matches ); // preserve order of sticky posts
        $query->query_vars['orderby'] = 'post__in';
        $query->query_vars['post__in'] = array_merge( $matches, $query->query_vars['post__in'] );
    }
}
add_action( 'pre_get_posts', 'fwp_preserve_sticky_posts' );

This fulfills the purpose of separating sticky and normal posts, except I need to be able to sort the return of the $matches array but the following criteria, and NOT post ID:

'meta_key' => '_meta_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'

I have identified that I need to replace the ksort on $matches, but I don’t know how. Please may someone help?

Thanks!

Related posts