plugins – WordPress How To Order Post By Custom Meta Field + If They Are Same Order By Date


I want to custom sort my posts. I already did it by adding “mysort” meta key. Minimum and default value of “mysort” is 0. Then i saved all posts with value “0” of “mysort”. If i sort only like 5 posts (for ex assigned 5 for a post will shown first). All OTHER posts are sorted by ID. I want to sort the others BY DATE, NOT ID.

So, priority is mysort meta key then date. How can i do this? Firstly check mysort meta key then, if others has same “mysort” value, check dates and sort by date.

here is my code:

function my_pre_get_posts( $query ) {
    
    // do not modify queries in the admin
    if( is_admin() ) {
        
        return $query;
        
    }
    

    // only modify queries for 'event' post type
    if( isset($query->query_vars('post_type')) && $query->query_vars('post_type') == 'post' ) {
        
        $query->set('orderby', 'meta_value');   
        $query->set('meta_key', 'mysort');   
        $query->set('order', 'DESC'); 
        
    }
    

    // return
    return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');