In my previous answer (that I’ve deleted..), I suggested using custom SQL queries, which worked for me. However, since it didn’t work (well) for you, let’s try using this function:
function get_player_stats( $player_id ) {
$apps = 0; // Total appearances.
$subs = 0; // Total sub-appearances.
$goals = 0; // Total goals.
// Get all published `match` posts.
$posts = get_posts( [
'post_type' => 'match',
'posts_per_page' => -1,
] );
foreach ( $posts as $post ) {
for ( $n = 1; $n <= 18; $n++ ) {
// Check if the player is $player_id
$pl = get_post_meta( $post->ID, 'pl' . $n, true );
if ( $player_id == $pl ) {
$apps++;
// Check his sub-out appearance.
$so = get_post_meta( $post->ID, 'so' . $n, true );
$subs += $so ? 1 : 0;
// Check his sub-in appearance.
$si = get_post_meta( $post->ID, 'si' . $n, true );
$subs += $si ? 1 : 0;
}
// Check if he scored goal {$n}-th.
$s = get_post_meta( $post->ID, 's' . $n, true );
if ( $player_id == $s ) {
$goals++;
}
}
}
// WP_Query was called; so resets $wp_query
wp_reset_query();
return compact( 'apps', 'subs', 'goals' );
}
If you have more than 18 players (in any matches), change the 18
in the $n <= 18;
to the correct number of players; e.g. 20
as in $n <= 20;
.
And here’s how you could use the get_player_stats()
function, which returns an associative array with apps
, subs
, and goals
as the keys:
$stats = get_player_stats( $playerID );
//var_dump( $stats );
echo $stats['apps'] . ' apps, ' .
$stats['subs'] . ' subs, and ' .
$stats['goals'] . ' goals.<br>';
I hope this answer works for you, and let me know if you need any clarification (on any parts of the code). =)