我很难说远程API是否只允许您获取给定球员的统计数据,但是。。。还有另一种方法,我会尽可能减少对远程API的请求数。。。
class Remote_Player_API {
private static $instance;
private $remote_data;
public static function init() {
if ( ! self::$instance ) {
self::$instance = new Remote_Player_API();
}
}
protected function __construct() {
$this->register_shortcodes();
}
protected function get_remote_api_data() {
// you can also use transients here and cache remote responses for some time to optimize API calls even more
if ( ! $this->remote_data ) { // obtain remote data only, if we haven\'t done it already, so the request will be done only once
$response = wp_remote_get(\'http://api-address-hidden-for-security/statsajax.php?action=rankedplayerslist&eventid=5\');
$this->remote_data = json_decode( utf8_encode( $response[\'body\'] ), TRUE );
}
return $this->remote_data;
}
protected function register_shortcodes() {
add_shortcode( \'individualPlayer\', array( $this, \'shortcode_callback_individualPlayer\' ) );
}
public function shortcode_callback_individualPlayer( $atts ) {
$atts = shortcode_atts( array(
\'player_number\' => 0, // you have to pass player_number as attribute
), $atts );
ob_start();
?>
<div class="s-players">
<div class="container">
<?php
foreach ( $this->get_remote_api_data() as $player ) :
if ( $player[\'Numero\'] != $atts[\'player_number\'] ) continue;
?>
<p><?php echo esc_html( $player[\'Evento\'] ); ?></p>
<p><?php echo (int)$player[\'Numero\']; ?></p>
<p><?php echo esc_html( $player[\'Jugador\'] ); ?></p>
<?php endforeach; ?>
</div>
</div>
<?php
return ob_get_clean();
}
}
Remote_Player_API::init();
免责声明:我在这里写了这段代码,所以可能有一些拼写错误;)