Support

Account

Home Forums Backend Issues (wp-admin) Sort by a customfield while showing all posts

Solved

Sort by a customfield while showing all posts

  • I’ve tried the approaches listed in your how-to ( http://www.advancedcustomfields.com/resources/how-to/orde-posts-by-custom-fields/ )

    The problem I’m having is that I have a custom post type of Vendors. They each have a rating using a Custom Field. I want to show all vendors but sort them by the custom field.

    So far each of the methods ends up showing me only the posts that have a rating set on them. Correctly ordered of course. But I need to see all the posts so those without ratings can get ratings.

  • Hi @kwoodall,

    Without seeing your code, all I can suggest is setting a Vendors rating default value to zero, or to a number outside the scope of your rating system (eg -1 or 11 could represent unrated on a scale of 0 to 10, depending on where you want the unrated Vendors to appear)
    You would then have a statement set up to print out “unrated” or something else suitable instead of the number.

    If this doesnt help, feel free to post the code (in back ticks please) that has got closest to what you want, and we’ll see what we can do.

    Cheers

  • Here’s the code from functions.php

    add_action( 'pre_get_posts', 'vendor_sort' );
    function vendor_sort( WP_Query $wp_query ) {
        // Ensure it is the global $wp_query
        if ( ! $wp_query->is_main_query() )
            return;
        
        if ( $wp_query->is_tax( 'vendor-type' ) ) {
            $wp_query->set( 'meta_key', 'crfp-average-rating' );
            $wp_query->set( 'orderby', 'meta_value_num' );
            $wp_query->set( 'meta_compare', '>' );
            $wp_query->set( 'order', 'DESC' );
        }
    }
  • Hi @kwoodall,

    setting the meta_key to ‘crfp-average-rating’ wont return any vendors that do not have that field. Depending on your setup, you could go with the suggestion above, or there may be a way to have no meta_key if ‘vendor-type’ only contains vendors you want displayed.

    cheers

  • Yeah, but without the meta key it won’t sort. I’m amazed this is something WordPress overlooked.

  • Hi @kwoodall,

    Would you consider implementing the original solution?

    If not, I was talking about getting all the results and manually sorting them, which is much more difficult.

    Cheers

  • I think we’ll have to implement that. Thanks anyways then!

    Kermit Woodall

Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘Sort by a customfield while showing all posts’ is closed to new replies.