Is it possible to query posts in the same order as assigned?

前端 未结 1 1406
北海茫月
北海茫月 2021-01-24 08:09

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

相关标签:
1条回答
  • 2021-01-24 09:07

    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

    0 讨论(0)
提交回复
热议问题