php - Wordpress Shortcode 循环遍历数据并将当前循环记录发送到自定义插件中的其他 Shortcode
问题描述
我正在创建一个插件,该插件当前从数据库返回商店库存。
现在我只是输出原始文本。
我想做的是输出数据并让其他简码呈现数据。
例如:
[store_inventory]
[/store_inventory]
上面的短代码将返回以下内容
array([0]=['item_name'='Juice', 'item_number' = '3dsj'], [1]=['item_name'='bread', 'item_number' = 'br3d']);
我想做的是让 store_inventory 短代码循环遍历数组,而不是返回原始数组。并将它循环的每个返回值传递给另一组简码,以便我可以将数据写入它自己的 html。
我的想法看起来像这样
[store_inventory] //This shortcode loops through the inventory array returned from the database
<div>
<p>[item_name]</p>//This shortcode returns current item_name being looped
<p>[item_number]</p>//This shortcode returns current item_number being looped
</div>
[/store_inventory]
我只是不确定如何处理遍历数组并将当前数据记录从数组传递到其他两个简码。
任何帮助,将不胜感激。
我知道从插件中吐出已经格式化的 HTML 很容易,但这意味着不能通过 wordpress 进行前端编辑或通过 wordpress 进行版本控制。
解决方案
您必须遍历每个项目store_inventory
并将数据传递到do_shortcode
.
我不确定您的store_inventory
简码如何,但请参见下面的示例:
function story_inventory_loop( $atts ) {
extract( shortcode_atts( array(
//attributes
), $atts ) );
$output = '<div>';
$args = array(
'post_type' => 'post', //your post type
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
$output .= '<p>'.
echo do_shortcode( '[item_name]' . get_the_title() . '[/item_name]' ).
'</p>'.
'<p>'.
echo do_shortcode( '[item_number]' . get_the_excerpt(). '[/item_number]' ).
'</p><!-- ends here -->';
endwhile;
wp_reset_query();
$output .= '</div>';
return $output;
}
add_shortcode('store_inventory', 'story_inventory_loop');
item_name
短代码:
function item_name_shortcode( $atts, $content = null ) {
return $content ;
}
add_shortcode( 'item_name', 'item_name_shortcode' );
item_number
短代码:
function item_number_shortcode( $atts, $content = null ) {
return $content ;
}
add_shortcode( 'item_number', 'item_number_shortcode' );
希望这可以帮助。
推荐阅读
- r - 如何处理这个错误?“在 `[<-.factor`(`*tmp*`, i, value = "WEN\\UA") 中:无效的因子水平,NA 生成”
- date - Pyspark from_unixtime (unix_timestamp) 不转换为时间戳
- javascript - 在桌面和移动设备上检测点击(或触摸)的最可靠方法是什么?
- javascript - react-native 扫描蓝牙设备
- sql-server - 未解决的对从数据迁移助手评估报告的 sys.objects 的引用以迁移到 Azure
- java - 无法使用 Maven 构建应用程序,我可以在本地运行代码,但无法在 heroku 上部署
- node.js - nodejs Dialogflow v2 从履行中关闭对话
- javascript - 如何修复 JS 不适应新的 HTML 输入
- python - 继续在带有 if 语句的 for 循环中不起作用(“继续”在循环中不正确)
- ios - 语音识别和音频播放在模拟器上工作但不在 iPhone 上?