在每次Rest API调用股票符号名称列表后更改变量,直到在Wordpress中完成列表



我正在尝试使用alphavantage REST API通过高级自定义字段输出股价。我现在的问题是,我不知道如何创建一个股票符号名称列表(我们有特定的股票要检查(,在检查完所有股票之前,它会更改每次调用。

这是我在functions.php 中当前的Wordpress代码


/* Register Stock Price Custom Post Type */
add_action('init', 'register_aktienpreise_cpt');
function register_aktienpreise_cpt(){
register_post_type('aktienpreise', [
'label' => 'Aktienpreise',
'public' => true,
'capability_type' => 'post'
]);
}
add_action( 'wp_ajax_nopriv_get_aktienpreise_from_api', 'get_aktienpreise_from_api' );
add_action( 'wp_ajax_get_aktienpreise_from_api', 'get_aktienpreise_from_api' );
/* Initialize Function */
function get_aktienpreise_from_api(){
/* Set Log File */
$file = get_stylesheet_directory() . '/report.txt';

/* Declare Current Symbol Variable and check if its not empty */
$current_symbol = ( ! empty($_POST['current_symbol']) ) ? $_POST['current_symbol'] : '';
$aktienpreise = [];

/* Results output for AlphaVantage Rest API + APIKEY - Add Current Symbol Set for each API Call */
$results = wp_remote_retrieve_body( wp_remote_get('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&apikey=demo&symbol=' . $current_symbol_set ));
file_put_contents($file, "Current Symbol: " . $current_symbol. "nn", FILE_APPEND);
// turn it into a PHP array from JSON string
$results = json_decode( $results );   

// Either the API is down or something else spooky happened. Just be done.
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
/* Change Current Stock Symbol for the next call until empty */
$current_symbol = $current_symbol + $current_symbol_set;

/* Repeat Calls until results are empty */
wp_remote_post( admin_url('admin-ajax.php?action=get_aktienpreise_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_symbol' => $current_symbol
]
] );
}

在这个部分

/* Change Current Stock Symbol for the next call until empty */
$current_symbol = $current_symbol + $current_symbol_set;

我想要一份我想检查的具体股票清单(例如苹果、IBM等(

目标是,在每次调用时,变量都会更改为下一只股票(比如说第一次调用苹果,第二次调用IBM(,然后将这些变量写入特定的ACF字段,我可以在我们网站的表格中展示这些字段。

如果restapi url只是增加了数量,那就很容易了,但我该如何使用诸如";IBM";等

此外,如果有更简单的解决方案,请告诉我,因为我对RESTAPI相当陌生。一般来说,目标是只在我们网站的表格中显示特定股票的当前股价,最好是在ACF字段中,这样我们就可以计算价格的数学公式(例如,另一个表格字段的价格x 2(。

谢谢大家抽出时间来帮助我!

为什么不为股票符号使用数组,并在循环中调用AlphaVantage API?

我给你举个简单的例子:

$my_symbols = [
'IBM',
'Microsoft',
'Tata'
];
foreach( $my_symbols as $current_symbol )  // iterate through the array elements
{
//... make the API calls to AlphaVantage 
//... do any other business logic, like storing the API result in file or update the stocks, etc..
}

需要记住的一点是,您应该确保脚本不会超时。因此,将max_execution_time增加到一个更高的值。

此外,您不必在这里调用自己的API。我的意思是,你不必对自己的网站进行wp_remote_post()

最新更新