【发布时间】:2019-10-09 12:54:39
【问题描述】:
我知道有办法做到这一点,但是,我很难理解它。这是我的问题。
我有一个短代码,可以触发一个引入商店库存的功能。我对用 HTML 返回的数据进行格式化。我的插件已经使用以下短代码 ['inventory']
如果可能的话,我想做的是在同一个函数中创建更多的短代码,例如[product_id]
希望在我循环遍历记录时,从同一个函数中将当前记录 product_id 作为该短代码值。
还将一些 WordPress 主题元素与简码结合使用。
假设库存短代码返回以下内容
<div>
<h1>Product ID {$product_id}</h1>
<p>Price $price</p>
</div>
并循环遍历每个产品,因此如果有 4 个产品,它将输出上述 HTML 4 次。
我使用的主题允许我创建特定于我的主题的按钮,我不想将这些按钮硬编码到我的代码中。
我想做的是以下
[inventory]
['record']
//Insert theme buttons using themes builder
<button value=['product_id']>Get more info</button>
['/record]
[/inventory]
所以我想做的是拥有库存,生成要输出的数据,而不是循环并输出 id,而是循环并将数据传递给 ['record'] 短代码,然后拥有它标签使用每条记录下方的按钮呈现输出。并为按钮值提供 product_id 短代码,它将保存当前记录的产品 ID。
我想说 do_shortcode 涉及到,但我不太确定如何实现。
感谢任何帮助
我已尝试阅读文档。
function inventory($atts, $content = null){
extract(shortcode_atts(array(
'storeid' => 'default',
), $atts));
//query that returns the store inventory
$query;
//Output formatted results FYI there is a whole function that but it pretty much just loops through the $query results.
foreach($query as $queryResult){
echo $queryResult;
}
}
add_shortcode('inventory', 'inventory');
<div>
<h1>Product ID {$product_id}</h1>
<p>Price $price</p>
</div>
<button value="apple">Get More Info</button>
更多信息
所以我有一个正在处理的项目,但我很难思考如何使用嵌套的短代码。
这就是我所拥有的
[inventory store=some_store_id category=fruit]
此短代码当前从数据库[[0]="product_id"=>['name'=>'apple', 'price'=>'2.00'],[1]="another_product_id"=>['name'=>'apple', 'price'=>'2.00']]返回以下内容
我想拥有这样的东西
<div>
[inventory store=some_store_id category=fruit]
[individual_product]
<div>
<h1>[product_id]</h1>
</div>
<div><h2>[name]</h2></div>
<div><p>[price]</p></div>
[/individual_product]
[/inventory]
</div>
【问题讨论】:
-
$contentof your inventory 函数包含 [inventory] 短代码标签之间的所有内容。您可以执行一些查找和替换代码以将产品 ID 放入其中,删除此处非常像模板标签而不是短代码的 [记录] 标签,然后在修改后的字符串上调用do_shortcode以处理主题的任何短代码生成器已添加。我正在测试并输入答案。 -
如果您真的想使用另一个短代码进行记录并传入 id,您可以在
do_shortcode( [record product_id=4 ] );等短代码字符串上调用 do_shortcode -
因此,当您在记录中传入记录简码并将 product_id 设置为 4 时,是否允许记录简码访问 product_id 值?或者您是说创建记录短代码并为其赋予 product_id 属性,然后在 do_shortcode 中设置该属性?
-
使用 str_replace 在第一个短代码内设置内容的属性值,然后在该字符串上调用 do_shortcode。现在用代码格式化答案...
-
为此目的使用 add_filter() 怎么样? Shortcode API 文档 codex.wordpress.org/Shortcode_API 提供了关于嵌套短代码的建议,并提到 add_filter 作为一种方法。
标签: php wordpress shortcode wordpress-plugin-creation