How do I sort WordPress posts by a meta_key contained inside an array?

Viewed 37

I'm trying to sort the WordPress Loop using action hook pre_get_posts.

I want to sort using a custom post metadata value.

I have post metadata named post_rank_cache which is an array. Inside that array is a key named hot_rank_score. I want to sort my posts by the value of hot_rank_score.

The problem is that I don't know how to set hot_rank_score as the meta_key because it's inside the metadata array of post_rank_cache.

Here is a visual representation of the metadata on my post:

$post_metadata = array(
    'some_metadata' => 2341234,
    'some_other_metadata' => 84,
    'some_more_metadata' => 'I am a string',
    'post_rank_cache' => array( //This is the key for the metadata array
            'some_key' => 35,
            'another_key' => 'blah',
            'hot_rank_score' => 10123.183 //This is the actual key I want to use for my sort
        )
);

This is the function I'm using. As you can see, I have no idea how to set the meta_key:

function modify_loop_for_loggedin_users( $query ) {
    if ( is_user_logged_in() && $query->is_home() && $query->is_main_query() && ! is_admin() ) {
        $query->set( 'orderby', 'meta_value_num' );
        $query->set( 'meta_key', ????? );
    }
}
add_action('pre_get_posts','modify_loop_for_loggedin_users');
0 Answers
Related