Skip to content

Instantly share code, notes, and snippets.

@kadimi
Last active February 22, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kadimi/122890d385362f94fc6fcf41c0f4667a to your computer and use it in GitHub Desktop.
Save kadimi/122890d385362f94fc6fcf41c0f4667a to your computer and use it in GitHub Desktop.
SportsPress - Make all teams current when importing players
<?php
/**
* Add this code to your website, I recommend adding it using the plugin Code Snippets.
* Disable or delete the snippet as soon as you finish importing players.
* `$treshold_in_seconds` should be a little higher than the import duration in seconds.
*
* @author Nabil Kadimi
* @link https://themeboy.com
*/
add_action( 'admin_init', function() {
/**
* How long to consider a player newly imported.
*/
$treshold_in_seconds = 10;
/**
* Only admins.
*/
if ( ! current_user_can( 'manage_sportspress' ) ) {
return;
}
/**
* Get newly imported players.
*/
$newly_imported_players = get_posts( [
'post_type' => 'sp_player',
'date_query' => [
'after' => date( 'Y-m-d H:i:s', strtotime( "-$treshold_in_seconds seconds" ) ) ,
],
'meta_key' => '_sp_import',
'meta_value' => '1',
'meta_compare' => '=',
] );
/**
* Set all players teams to current.
*/
foreach ( $newly_imported_players as $player ) {
/**
* Merge all teams.
*/
$updated_player_current_teams = array_unique ( array_merge ( get_post_meta( $player->ID, 'sp_past_team' ), get_post_meta( $player->ID, 'sp_current_team' ) ) );
/**
* Delete old meta values.
*/
foreach( [ 'sp_current_team', 'sp_past_team', 'sp_team' ] as $meta_key ) {
delete_post_meta( $player->ID, $meta_key );
}
/**
* Save new meta values.
*/
array_walk( $updated_player_current_teams, function( $team_id ) use ( $player ) {
add_post_meta( $player->ID, 'sp_current_team', $team_id );
add_post_meta( $player->ID, 'sp_team', $team_id );
} );
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment