WordPress: How to sort content by ACF custom field?
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.
wharfdale
Hi, I am Jordan. I am a front end developer with a lot of questions! ha.
Updated on August 21, 2022Comments
-
wharfdale over 1 year
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
FreeIn 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; ?>
-
wharfdale over 9 yearsIn addition to this, do you know how I may be able to get all the appropriate listings, in order as previously requested but only from the category you're currently in? I am getting the results of Ultimate Plus etc levels from every category whilst in any category right now.
-
Andrew Fielden over 9 yearsIf you only want one of the categories then add 'meta_value' => 2, // for business etc..
-
vladkras almost 9 yearsgood example, BUT why 1.
'numberposts' => -1
is added here, I don't see OP wants to unlimit query 2. this will spoil all your already published posts -
vladkras almost 9 yearsI need exactly what OP asks: sort the posts in the order these values are
-
Antonios Tsimourtos about 7 years@AndrewFielden Could you help me with this ? I am in a same situation with a little more complex work but can't seem to figure it out.