WordPress: How to sort content by ACF custom field

2019-05-06 14:29发布

问题:

With use of the Advanced Custom Fields plugin I created a select dropdown which contains 6 membership types. All of my 'listings' using this custom field are assigned one of the 6.

I'd like to display all 'listings' by:

Ultimate Plus
Ultimate
Professional
Commercial
Business
Free

In this particular order, so those paying for the highest level membership have their 'listing' appear at the top of the page.

I expected it to be similar to this which I just found but unsure exactly:

// args
$args = array(
'post_type'  => 'directory_listings',
'meta_key'   => 'free',
'orderby'    => 'meta_value_num',
'order'      => 'ASC',
'meta_query' => array(
    array(
        'key'     => '#',
        'value'   => array( #, # ),
        'compare' => 'IN',
    ),
),
);

// query
$wp_query = new WP_Query( $args );

?>

<?php if (have_posts()) : ?>

    <?php
    while( $wp_query->have_posts() ) {
        the_post();
        ldl_get_template_part('listing', 'compact');
        ldl_get_featured_posts();
    }
    ?>

<?php else : ?>

<?php endif; ?>

回答1:

You are almost there

If you change the choices in the Advanced Custom Fields to

1 : Free
2 : Business
3 : Commercial
4 : Professional
5 : Ultimate
6 : Ultimate Plus

And then the default to 1

By doing this you are setting the values to the number and the default is the Free value. In the admin screen you will be presented with the text value.

Then to do your query try this for the query

$wp_query = get_posts(array(
  'numberposts' => -1,
  'post_type' => 'directory_listings',
  'meta_key' => 'membership_type',
  'orderby' => 'meta_value',
));

It will get all of the posts that have a value set and order it by the membership type descending which is what you want.

I have tried this on my local setup to confirm this.