我有一个循环,在这里我循环遍历我的CPT的每个帖子,获取每个帖子的标题和内容,并将其放入一个数组中。这没问题。
但碰巧我创建了一个可重复的字段Advanced Custom Fields 这些职位都有。这些字段包含我要添加到数组中的图像和标题。
这是我当前的代码
$args = array(
\'posts_per_page\' => \'-1\',
\'post_type\' => \'work\',
\'orderby\' => \'ID\',
\'order\' => \'DESC\',
);
$data = array(\'work\' => array());
$loop = new WP_Query($args);
if( $loop->have_posts() ):
while( $loop->have_posts() ): $loop->the_post();
$id = $loop->post->ID;
$data[\'work\'][$id] = array(
\'title\' => apply_filters( \'the_title\', $loop->post->post_title ),
\'content\' => apply_filters( \'the_content\', $loop->post->post_content ),
);
endwhile;
endif;
wp_reset_postdata();
哪些输出
{
"work":{
"45":{
"title":"Project 7",
"content":"<p>I am the other text.<\\/p>\\n"
},
}
}
我想要的是这样的
{
"work":{
"45":{
"title":"Project 7",
"content":"<p>I am the other text.<\\/p>\\n"
"items":{
"1":{
"caption":"I\'m an image",
"url":"www"
},
"2":{
"caption":"I\'m another image",
"url":"www"
},
}
},
}
获取不同附件的循环如下所示。。
<?php if(get_field(\'work\')): ?>
<?php while(has_sub_field(\'work\')):
$attachment_id = get_sub_field(\'image\');
$caption = the_sub_field(\'caption\');
$image = wp_get_attachment_image_src( $attachment_id, work );
endwhile; ?>
<?php endif; ?>
。。但我无法理解如何将这个循环的结果放入数组中。如果有人能给我指出正确的方向,我会很高兴的!谢谢
最合适的回答,由SO网友:birgire 整理而成
我认为这不是一个限制性的Wordpress问题,但你可以试试
$args = array(
\'posts_per_page\' => \'-1\',
\'post_type\' => \'work\',
\'orderby\' => \'ID\',
\'order\' => \'DESC\',
);
$data = array(\'work\' => array());
$loop = new WP_Query($args);
if( $loop->have_posts() ):
while( $loop->have_posts() ): $loop->the_post();
$id = $loop->post->ID;
$attachments=array();
if(get_field(\'work\')):
while(has_sub_field(\'work\')):
$attachment_id = get_sub_field(\'image\');
$caption = the_sub_field(\'caption\');
$image = wp_get_attachment_image_src( $attachment_id, \'work\' );
$attachments[$attachment_id]=array("caption"=>$caption,"url"=>$image);
endwhile;
endif;
$data[\'work\'][$id] = array(
\'title\' => apply_filters( \'the_title\', $loop->post->post_title ),
\'content\' => apply_filters( \'the_content\', $loop->post->post_content ),
\'items\' => $attachments;
);
endwhile;
endif;
wp_reset_postdata();