如何从多维数组内的WP_Query对象中获取post_content、ID等文章数据
从WP_Query对象提取文章字段的解决方法
你当前的代码存在可优化点:循环遍历时你将整个WP_Query对象存入了$master数组,实际使用只需要存储当前文章的相关字段即可,既节省内存也方便后续调用。两种实现方案如下:
方案1:优化存储逻辑(推荐)
在遍历文章的阶段直接提取所需字段存入数组,后续调用更简单:
global $post; $args = array( 'post_type' => 'history', 'order' => 'ASC' ); $master = []; $post_query = new WP_Query($args); if ($post_query->have_posts() ) { while ($post_query->have_posts()) { $post_query->the_post(); /* 获取文章日期 */ $year = get_the_date( 'Y' ); $mon = get_the_date( 'M' ); // 直接提取所需字段存入数组 $post_data = [ 'post_id' => get_the_ID(), // 文章ID 'post_content' => get_the_content(), // 文章内容 'pagename' => $post->post_name, // pagename对应文章的slug字段 'categories' => get_the_category(), // 文章分类对象数组 ]; $master[$year][$mon][] = $post_data; } foreach ($master as $masterkey => $mastervalue) { echo "<p>"; echo "年份: ". $masterkey . "<br>"; foreach($mastervalue as $mon => $post_list) { echo "月份: " . $mon . "<br>"; // 遍历当月所有文章输出字段 foreach($post_list as $post_item) { echo "文章ID:" . $post_item['post_id'] . "<br>"; echo "文章别名:" . $post_item['pagename'] . "<br>"; echo "文章内容:" . $post_item['post_content'] . "<br>"; // 输出分类名称 echo "文章分类:"; foreach($post_item['categories'] as $cat) { echo $cat->name . ' '; } echo "<br><hr>"; } } echo "</p>"; } } wp_reset_postdata();
方案2:从现有存储的WP_Query对象直接提取
如果你不想修改存储逻辑,直接从当前$value中存储的WP_Query对象提取字段的代码如下:
foreach($mastervalue as $key => $value) { echo "key: " . $key . "<br>"; // WP_Query的posts属性存储了所有查询到的文章对象 foreach($value->posts as $post_item) { echo "文章ID:" . $post_item->ID . "<br>"; echo "文章内容:" . $post_item->post_content . "<br>"; echo "文章别名:" . $post_item->post_name . "<br>"; // 传入文章ID获取对应分类 $categories = get_the_category($post_item->ID); echo "文章分类:"; foreach($categories as $cat) { echo $cat->name . ' '; } echo "<br>"; } }
内容的提问来源于stack exchange,提问作者la_petite_kozel
相关产品推荐
相关产品推荐

