Query posts using meta_key

After poking around for a day and half, I found a solution.

There was nothing in my theme that was controlling the search result besides the form actions, which were:

<!-- Search Result Page -->
<form action="<?php echo home_url("https://wordpress.stackexchange.com/");?>" method="get" data-javo-patch-form-for-result>
<input type="hidden" name="post_type" value="item">
<input type="hidden" name="location" value="<?php echo $javo_query->get('location');?>" data-javo-sf-location>
<input type="hidden" name="s" data-javo-sf-keyword>
</form>
<!-- /data-javo-patch-form-for-result : Go to Archive Page -->

So drawing upon a code like this (which I have before) wasn’t an option and I couldn’t figure it out for this particular keyword search.

remove_all_filters('posts_orderby');
    $args                   = Array(
        'post_type'         => 'item'
        , 'meta_key' => 'level'
        , 'orderby' => array('meta_value_num' => 'ASC', 'title' => 'ASC')
        , 'post_status'     => 'publish'
        , 'posts_per_page'  => $ppp
        , 'paged'           => $page
            );
            $the_query = new WP_Query( $args );

Instead, the search function was drawing upon query.php in wp-includes. I went about modifying this file, but found it too difficult.

The solution was to use pre_get_posts and target only the search query.

add_action( 'pre_get_posts', 'custom_get_posts' );
function custom_get_posts( $query ) {
if ( is_admin() || ! $query->is_main_query() )
    return;
  if ( $query->is_search() ) {
$query->set( 'meta_key', 'level' );
$query->set('orderby', array('meta_value' => 'ASC', 'title' => 'ASC'));
}
}

Hopefully this saves someone from a massive headache.