Skip to content

Instantly share code, notes, and snippets.

@ViewFromTheBox
Created December 21, 2017 01:53
Show Gist options
  • Select an option

  • Save ViewFromTheBox/fe4d13914ac9e7c74462bfdbf8dc5d79 to your computer and use it in GitHub Desktop.

Select an option

Save ViewFromTheBox/fe4d13914ac9e7c74462bfdbf8dc5d79 to your computer and use it in GitHub Desktop.
<?php
class Sports_Bench_Team_REST_Controller extends WP_REST_Controller {
/**
* Create one item from the collection
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_Error|WP_REST_Response
*/
public function create_item( $request ) {
$item = $this->prepare_item_for_database( $request );
if ( function_exists( 'sports_bench_rest_add_team') ) {
$data = sports_bench_rest_add_team( $item );
if ( is_array( $data ) ) {
return new WP_REST_Response( $data, 201 );
} else {
echo 'not created';
return $data;
}
}
return new WP_Error( 'cant-create', __( 'message', 'text-domain'), array( 'status' => 500 ) );
}
}
function sports_bench_rest_add_team( $item ) {
global $wpdb;
$table_name = $wpdb->prefix . 'sb_teams';
$team_name = $item[ 'team_name' ];
$slug_test = $wpdb->get_results( "SELECT * FROM $table_name WHERE team_name LIKE $team_name" );
if ( $slug_test == [] ) {
$result = $wpdb->insert( $table_name, $item );
echo $wpdb->last_error;
if ( $result ) {
return $item;
} else {
return new WP_Error( 'error_team_insert', __( 'There was an error creating the team. Please check your data and try again.', 'sports-bench' ), array( 'status' => 500 ) );
}
} else {
return new WP_Error( 'error_team_insert', __( 'This team has already been created in the database. Maybe try updating the team.', 'sports-bench' ), array( 'status' => 500 ) );
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment