Order posts by title and custom field value?

I want to order posts by title, but always show featured posts first. I have the code below to order posts by title. Now I would like to always show posts first that have the metafield 'wiloke_listgo_toggle_highlight' with the value '1'. How can I accomplish this?

/* Order Posts Alphabetically */
function prefix_modify_query_order( $query ) {
  if ( is_main_query() ) {

    $args =  array( 'title' = 'ASC' );

    $query-set( 'orderby', $args );
  }
}
add_action( 'pre_get_posts', 'prefix_modify_query_order' );

Topic pre-get-posts wp-query custom-field Wordpress

Category Web


My first attempt to help you with solving your problem would be to do something like this :

/* Order Posts Alphabetically */
function prefix_modify_query_order( $query ) {
  if ( is_main_query() ) {

    $query->set(
        'meta_query', array(
            'relation' => 'AND',
            'query_highlight' => array(
                'key'   => 'wiloke_listgo_toggle_highlight',
                'value' => '1',
                'compare' => '='
            )
        )
    );

    $query->set(
        'orderby', array( 
            'title' => 'ASC',
            'query_highlight'   => 'ASC',
        )
    );
  }
}
add_action( 'pre_get_posts', 'prefix_modify_query_order' );

Source : https://codex.wordpress.org/Class_Reference/WP_Meta_Query#Usage

The code should start ordering posts by title ASC and also take posts with your custom key with value to 1.

Note : Did not test it so I suggest you to comment this if their is any bugs.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.