如何通过获取post meta然后写入CSV来过滤自定义字段数组

时间:2016-06-02 21:03:40

标签: php wordpress csv foreach

我有一个我在整个网站中使用的代码段,它从自定义字段"menu_listing"中读取产品ID,并在无序列表中显示内容(如图像,标题,超链接等)。我在我的网站上的不同地方使用它(例如https://eatgoodathome.com/order/menu)。

我正在尝试将我的导出订单中的客户订单信息旁边的产品名称列表输出到CSV插件。以下是与"menu_listing"相关的代码。

global $post; 

// Date Range Parameters
   $today = date("Y-m-d");
   $next = date("Y-m-d", strtotime( "$today +2 weeks"));

// Query current menu based on date
   $menu_args = array(
        'post_type'=>'single_menu',
        'posts_per_page' => 1,
        'meta_query' => array( 
         array(
             'key' => "delivery_date",
             'value' =>  array( $today, $next ),
             'type'  => 'date',
             'compare' => 'BETWEEN'
             ),
         ));

// Display custom field
   $menu = new WP_Query( $menu_args );
   if ( $menu->have_posts() ) {
     while ( $menu->have_posts() ) {
                $menu->the_post();
            }

        // This is the custom field, content looks like this: [{"id":"9115"},{"id":"8256"},{"id":"8539"},{"id":"5586"}]
        $current_menu = json_decode( stripcslashes( get_post_field( "menu_listing", $post->id ) ) );


     if( $current_menu ){
           foreach( $current_menu as $single_block ) {

             if( $single_block->id ) { 
                      $dishes = get_post( $single_block->id )->post_title;
     }}}}

//Output CSV cells
    $row = array( $dishes );

在上面显示的状态中,它遍历所有产品,并仅显示最后一个产品的名称。我尝试使用implode(),explode(),另外一个foreach() - 这些似乎都是错误方向的一步,输出一个空白列。我错过了什么?

2 个答案:

答案 0 :(得分:0)

看起来你正在为每次迭代重新分配$dishes的值,这就是为什么你只看到最后一项的名字。试着这样做:

$dishes[] = get_post( $single_block->id )->post_title;

这样,您将在每次迭代时创建$dishes数组的新索引,而不是重新分配其值。然后,您只需指定$row = $dishes

答案 1 :(得分:0)

解决方案:我的问题中的代码循环遍历数组,只给出了数组中的最后一项。我的目标是遍历每个键/值对,将值(" id")转换为title,并让每个标题填充我的csv列。我的解决方案涉及废除foreach语句,并通过其偏移量请求循环中的每个数组,然后在csv文件中为其分配一列。

    //Output for CSV
    $output = fopen('php://output', 'w');

if ( $menu->have_posts() ) {
 while ( $menu->have_posts() ) {
            $menu->the_post();
        }

    // This is the custom field, content looks like this: [{"id":"9115"},{"id":"8256"},{"id":"8539"},{"id":"5586"}]
    $current_menu = json_decode( stripcslashes( get_post_field( "menu_listing", $post->id ) ) );


    $dish1 =  get_post( $current_menu[0]->id )->post_title;
    $dish2 =  get_post( $current_menu[1]->id )->post_title;
    $dish3 =  get_post( $current_menu[2]->id )->post_title;

 // Validate for 4th array item, if exists
    if( sizeof($current_menu) === 4 ) {
    $dish4 =  get_post( $current_menu[3]->id )->post_title;
    } else {
    $dish4 =  "";
    }
}

//Output CSV cells
$row = array( $dish1, $dish2, $dish3, $dish4 );
        fputcsv( $output, $row );