If I understood correctly, that Peak Postion is based on longest period the song was in same position (which I found odd), here's what you could do:
Have three meta fields
:: song_meta_peak
:: song_meta_weeks_now
:: song_meta_weeks_peak
First time song enters the list, you set peak
meta to whatever the position is and both weeks_now
and weeks_peak
metas to 1
Every week, if position is not changed, you add 1 to weeks_now
meta
Whenever the position changes you first check the weeks_now
meta to find out how long the song has been in the previous position, and if it exceeds the weeks_peak
you set peak
meta to that previous position and override weeks_peak
to match the weeks_now
. After that you set weeks_now
back to 1
.
Hope that helps
Code Example
$oldWeeks = get_post_meta( $post_id, 'song_meta_weeks_now', true );
$oldWeeksPeak = get_post_meta( $post_id, 'song_meta_weeks_peak', true );
if ( POS. NOT CHANGED ) {
update_post_meta( $post_id, 'song_meta_weeks_now', $oldWeeks + 1 );
} else {
update_post_meta( $post_id, 'song_meta_weeks_now', 1 );
if ( $oldWeeks > $oldWeeksPeak ) {
update_post_meta( $post_id, 'song_meta_weeks_peak', $oldWeeks );
update_post_meta( $post_id, 'song_meta_peak', PREVIOUS POS. );
}
}