【发布时间】:2021-12-24 01:03:05
【问题描述】:
我有一个带有 wp_query 循环的短代码,它输出一个类别列表作为导航和帖子列表。原始代码要复杂得多,因此我尝试删除不必要的行以便更好地理解。
function filter_shortcode($atts, $content = null) {
global $post;
$attributes = shortcode_atts(
array(
'type' => '',
'num' => -1
), $atts);
$args = array(
'post_type' => $attributes["type"],
'posts_per_page' => $attributes["num"]
);
$post_query = new WP_Query($args);
$master_array = array();
if ($post_query->have_posts() ) {
while ($post_query->have_posts()) {
$post_query->the_post();
$nav_arr = wp_get_post_terms( get_the_ID(), 'solutions_category' );
// Problem here
foreach($nav_arr as $nav_value ) {
$nav = $nav_value->name;
}
$box_tooltip = '<div>Lorem Ipsum</div>';
$info_box_title = '<h5 style="margin-bottom: 0;">' . strtoupper($post->post_title) . '</h5>';
if (!($master_array[$nav])) {
$master_array[$nav] = array();
array_push(
$master_array[$nav],
[
'icon_title' => $info_box_title,
'tooltip' => $box_tooltip,
]
);
} else {
array_push(
$master_array[$nav],
[
'icon_title' => $info_box_title,
'tooltip' => $box_tooltip,
]
);
}
} // End of while have_posts
wp_reset_postdata();
/* Foreach master array */
foreach ((array)$master_array as $master_key => $master_value) {
/* Navigation */
$navigation .= '<div>'. $master_key .'</div>';
foreach($master_value as $query_key => $query_value) {
$output_inner = '';
foreach ($query_value as $object_key => $object_value) {
$output_inner .= $object_value;
}
/* Content */
$output_outer .= '<div class="'. $master_key .'">'. $output_inner .'</div>';
} // end foreach mastervalue
} // end foreach master
} // end if have posts
return '
<div style="margin-bottom: 30px;">'. $navigation .'</div>
<div>'. $output_outer .'</div>
';
}
add_shortcode('cpt_filter', 'filter_shortcode');
输出:
问题是,如果帖子有多个类别,该函数将只输出一次帖子。例如,“GOOGLE WORKSPACE”有两个类别——“协作”和“交流”,但它只输出一次。
如何输出“GOOGLE WORKSPACE”与其拥有的类别数量一样多,并指定其自己的类别类?
var_dump($nav_arr) 在“GOOGLE WORKSPACE”迭代后:array(2) { [0]=> object(WP_Term)#3992 (10) { ["term_id"]=> int(825) ["name"]=> string(13) "Collaboration" ["slug"]=> string(13) "collaboration" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(825) ["taxonomy"]=> string(18) "solutions_category" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(8) ["filter"]=> string(3) "raw" } [1]=> object(WP_Term)#3986 (10) { ["term_id"]=> int(824) ["name"]=> string(13) "Communication" ["slug"]=> string(13) "communication" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(824) ["taxonomy"]=> string(18) "solutions_category" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(8) ["filter"]=> string(3) "raw" } }
尝试检查 $nav_arr 是否有多个值 if (sizeof($nav_arr) > 1) { .... } 并创建单独的数组,但卡住了。
【问题讨论】:
标签: php arrays wordpress shortcode