首页 > 解决方案 > 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 进行版本控制。

标签: phpwordpress

解决方案


您必须遍历每个项目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' );

希望这可以帮助。


推荐阅读