Support

Account

Home Forums General Issues Sort order of several ACF Fields

Solving

Sort order of several ACF Fields

  • I’m trying to sort on several field’s values. The two fields I would like to sort: builder_lot & builder_title.

    It is working for the first one but need help understanding how to add the second sort option.

    $builder_args = array(
    ‘post_type’ => ‘builders’,
    ‘posts_per_page’ => -1,
    ‘meta_key’ => ‘builder_lot’,
    ‘orderby’ => ‘meta_value’,
    ‘order’ => ‘ASC’
    );

    $builder_query = new WP_Query( $builder_args );

    if ( $builder_query->have_posts() ) {
    while ( $builder_query->have_posts() ) {
    echo $builder_lot.’ – ‘.builder_title;
    } // end while
    } // end if

    example:

    builder_lots values like 4, 55, 60, etc.
    builder_title values like ‘Builder Name 1’, ‘Builder Name 2’, ‘Builder Name 3’, etc.

    Looking to sort both ASC with builder_lot first, then by builder_title.

    Output:

    40 – Builder Name 1
    40 – Builder Name 2
    40 – Builder Name 3
    55 – Builder Name 1
    55 – Builder Name 2
    55 – Builder Name 3
    60 – Builder Name 1
    60 – Builder Name 2
    60 – Builder Name 3

    Thanks!

  • You have to use a meta query with multiple values and clauses.

    See the example of using clauses on the documentation for WP_Query() Order & Orderby Parameters. The example is titled “‘orderby’ with multiple ‘meta_key’s” and is currently the 10th example given.

    Note, in your case you would use “EXISTS” for the compare setting on both meta keys.

  • I guess I’m missing something as this now returns nothing:

    
    $builder_args = array(
    	'post_type' => 'builders',
    	'posts_per_page' => -1,
    	'meta_query' => array(
    		'relation' => 'AND',
    		'lot_clause' => array(
    			'key' => 'builder_lot',
    			'value' => 'meta_value',
    			'compare' => 'EXISTS',
    		),
    		'title_clause' => array(
    			'key' => 'builder_title',
    			'value' => 'meta_value',
    			'compare' => 'EXISTS',
    		), 
    	),
    	'orderby' => array( 
    		'lot_clause' => 'ASC',
    		'title_clause' => 'ASC',
    	),		  
    );
    

    I’m not sure if key=value parts of the clauses are correct.

    The link you provided says: “Note that a ‘meta_key=keyname‘ must also be present in the query.”

  • you don’t need 'value' => '' for either field and that could be causing the issue.

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

You must be logged in to reply to this topic.