wp query - Order posts by title and custom field value?

admin2025-01-07  4

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' );

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' );
Share Improve this question asked Jul 9, 2018 at 15:46 RobbTeRobbTe 2622 silver badges15 bronze badges 2
  • 2 you need to set orderby to an array like that ["meta_value" => "ASC", "title" => "ASC"] and set meta_key to "wiloke_listgo_toggle_highlight". – mmm Commented Jul 9, 2018 at 16:05
  • 1 As @mmm said but just take care because first you are reordering the admin too. and second if the meta_key not exists its won't show the posts at all. you can check if exists or if not exists but it will order the exists first all with 1 first all with 0 after and all the not exists last. – Shibi Commented Jul 9, 2018 at 16:15
Add a comment  | 

1 Answer 1

Reset to default 0

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736255279a269.html

最新回复(0)