Is it possible to query posts in the same order as

2019-03-01 04:07发布

问题:

I have a custom field named type, which is a a "radio button" data type and it has some choices. This custom field, is assigned to a custom post type named pproduct.

For example here are the choices of this custom field :

  • RED
  • BLUE
  • YELLOW
  • WHITE
  • BLACK

Only one can be selected from the above.

The below $args :

 $args = array(
      'post_type' => 'pproduct',
      'posts_per_page' => -1,
      'post_status'=>array('publish'),
      'product' => $category->slug ,
      'meta_query' => array(
          'relation' => 'AND',
          'type_clause' => array(
              'key' => 'type',
          ),
          'order_clause' => array(
              'key' => 'order',
          ),
      ),
      'orderby' => array(
              'type_clause' => 'DESC',
              'order_clause' => 'ASC',
      ),
  );

will query all posts of post type pproduct, and it will sort it by two custom fields. Type and order . It will sort it in an alphabetical order.

Is it possible to modify this and sort it by the same order as the types are assigned? Does anyone know what happens if i don't use order by? I can see it brings the posts but what is the "default order" if it's not assigned by me.

EDIT 1 : Something like this

回答1:

UPDATE:

I missunderstood your demand. If i get it right now, you want to make order as you assigned it in setting, simply like you write

  • RED
  • BLUE
  • YELLOW
  • WHITE
  • BLACK

That couldn't be achieved with WP query args, you will have to write your own database query to achieve this because query must know the order rules which is set by you (it does know alpabetical, numeric, date order etc. which can be simply derivated from field).

However if you could change values ACF to numeric (like u've posted in comment link) you win, then you will have to create translation array (to translate number to color name) if u will need to use value as color name/slug. So in ACF settings choices:

  • 1 : RED
  • 2 : BLUE
  • 3 : YELLOW
  • 4 : WHITE
  • 5 : BLACK

Query args will remain same (except type ordering DESC->ASC) and if you need to get the name from number, use this in loop:

$field = get_field_object( 'type' );
$value = $field['value'];
$color_name = $field['choices'][ $value ]; // this will be formated
$unformated_slug = sanitize_title( $color_name ); // change to lowercase and remove whitespaces etc..

// then you can work with $unformated_slug like your original field value eg:
if( $unformated_slug == 'red' ) {
    /* do something here */
}

Changing choice values to numbers is the most simplier way, anything other will be too complicated.

--

Default order of posts is by date. If you want to set your order automatically for all queries or only for custom post type queries, see https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts