我编写了一个插件,可以通过短代码从亚马逊产品广告 API 检索产品信息。当我从亚马逊检索结果时,我将每个单独的产品存储在瞬态中,这样我就不需要再次进行特定的调用。在我网站上使用此短代码的大多数页面上,它仅适用于单个产品。但是,在某个特定页面的情况下,我收到了
TooManyRequests
响应,因为我使用了短代码 20 或 30 次。
亚马逊 API 允许我一次传递多个产品,但考虑到我多次使用某个插件,我不确定如何才能做到这一点。
这是我现在如何调用插件的示例。
[mm-productlinking id="1" template="image"]
有没有办法在执行前收集多个短代码的使用,然后同时调用所有这些?也许是这样的?
[mm-productlinking-group]
some html code here
[mm-productlinking id="1" template="image"]
more html code here
[mm-productlinking id="2" template="image"]
and even more html code
[/mm-productlinking-group]
如果我做了这样的事情,我希望它是可选的,这样我就不会被迫包含
mm-productlinking-group
外部短代码。
想法?
感谢 Emiel 的指导,这就是我的想法。
<?php
class Group {
function __construct() {
add_shortcode('group', array($this, 'run'));
}
function get_attribute_from_child_shortcode($content, $attribute) {
// returns the post ID from each child shortcode contained in Group
}
function get_asins($post_ids) {
// retrieves Amazon ASIN ID from post meta, for posts referenced in a child shortcode
}
function run($attributes = [], $content) {
// only run when nested shortcodes are found
if ($content) {
$post_ids = $this->get_attribute_from_child_shortcode($content, 'id');
$asins = $this->get_asins($post_ids);
foreach (array_chunk($asins, 10) as $asin_group) {
$amazon_results = $this->amazon_api->get_items($asin_group);
}
return do_shortcode($content);
}
}
}
class Linking {
function __construct() {
add_shortcode('mm-productlinking', array($this, 'run'));
}
function run($attributes = []) {
$data_attributes = array_merge($data_attributes,[
'product_info' => $this->amazon_api->get_item($game_meta['asin']),
]);
return $data_attributes;
}
}
可以这样称呼
[mm-productlinking-group]
some html
[mm-productlinking id="276357"]
more html
[mm-productlinking id="276784"]
even more html
[mm-productlinking id="279208"]
html at the end
[/mm-productlinking-group]
在这种情况下,我会执行以下操作:
也可以这样调用,在这种情况下不使用组功能。
[mm-productlinking id="277880"]
我希望对这种方法有一些想法,因为我以前从未这样做过。