Support

Account

Home Forums General Issues Query relationship fields based on field value. Reply To: Query relationship fields based on field value.

  • If I am not missing anything, your problem is that you grab the reviews version numbers, but once you have found the highest version, you no longer know, which review that version number applies to, right?

    <?php
    // Fetch all reviews dealing with this game.
    $reviews = get_posts(array(
        'post_type'     => 'reviews',
        'meta_query'    => array(
            array(
                'key'         => 'related_games',
                'value'       => '"' . get_the_ID() . '"',
                'compare'     => 'LIKE'
            )
        )
    ));
    
    // An associative array of each review of each version.
    $version_array = [];
    
    foreach ( $reviews AS $k => $v ) {
    	
    	// Fetch the version.
    	$version = get_field( 'review_game_version' , $v->ID ) ?? false;
    	
    	// Ignore reviews that have no version.
    	if ( $version === false ) continue;
    	
    	// Save the version in the post object for later use.
    	$reviews[$k]->review_game_version = $version;
    	
    	// File this review by its game's version.
    	if ( $version_array[$version] ) {
    		$version_array[$version] = [];
    	}
    	$version_array[$version] = $v;
    }
    unset( $version );
    
    // Put the highest version at the end.
    ksort( $version_array );
    $highest_version = array_key_last() ?? false;
    
    // Make sure there is a highest version.
    if ( $highest_version !== false ) {
    	
    	// Iterate all reviews that are dealing with the highest version.
    	foreach ( $version_array[$highest_version] AS $review ) {
    		// Do something...
    	}
    }