Skip to content

Instantly share code, notes, and snippets.

@kadimi
Last active December 4, 2019 10:46
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/a36f1a3e241c29f0dcf0e4988f737fac to your computer and use it in GitHub Desktop.
Save kadimi/a36f1a3e241c29f0dcf0e4988f737fac to your computer and use it in GitHub Desktop.
Auto-create player lists in SportsPress
<?php
/**
* Auto-create player lists in SportsPress.
*
* This code will generate player lists for teams without one.
* It's useful if your SportsPress site has a lot of teams and you don't
* want to create player lists one by one.
*
* The code will only work when the parameter `sp_create_player_lists` is
* detected in the URL, @example, http://sp.box/?sp_create_player_lists=1.
*
* @license GPLv3+
*/
add_action( 'init', function() {
/**
* Settings.
*/
$settings = [
'sp_columns' => [
'goals',
'assists',
// 'yellowcards',
// 'redcards',
// 'etc...',
],
'sp_grouping' => '', // You can use 'position'
];
/**
* Verify that you're an admin.
*/
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
/**
* Verify that sp_create_player_lists is set in the URL.
*/
if ( ! array_key_exists( 'sp_create_player_lists', $_GET ) ) {
return;
}
/**
* Verifies that the team doesn't have a player list already.
*
* @param $team_post_id The team post ID.
*/
$team_has_player_list = function( $team_post_id ) {
return ( bool ) get_posts( [
'post_type' => 'sp_list',
'numberposts' => -1,
'posts_per_page' => -1,
'meta_key' => 'sp_team',
'meta_value' => $team_post_id,
] );
};
/**
* Creates player list.
*
* @param $team Team post object.
* @param $settings Settings (e.g. columns).
*/
$create_team_player_list = function( $team, $settings ) {
return wp_insert_post( [
/**
* Post attribtues.
*/
'post_status' => 'publish',
'post_title' => $team->post_title,
'post_type' => 'sp_list',
/**
* Metadata.
*/
'meta_input' => [
'sp_columns' => $settings[ 'sp_columns' ],
'sp_grouping' => $settings[ 'sp_grouping' ],
'sp_era' => 'current',
'sp_team' => $team->ID,
],
], true );
};
/**
* Loop through teams and create player lists where missing.
*/
$teams = get_posts( [
'post_type' => 'sp_team',
'numberposts' => -1,
] );
foreach ( $teams as $team ) {
if ( ! $team_has_player_list( $team->ID ) ) {
$create_team_player_list( $team, $settings );
}
}
/**
* All done! Let's redirect you to the player lists page.
*/
wp_safe_redirect( admin_url( 'edit.php?post_type=sp_list' ) );
exit;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment