add_filter( 'wp_get_nav_menu_items', 'wpcb_add_product_subcats_to_menu' );
if ( ! function_exists( 'wpcb_add_product_subcats_to_menu' ) ) {
/**
* wpcb_add_product_subcats_to_menu.
*
* @see https://wpcodebook.com/snippets/automatically-add-woocommerce-product-subcategories-to-categories-in-menu/
*/
function wpcb_add_product_subcats_to_menu( $items ) {
if ( is_admin() ) {
return $items;
}
$children_order = count( $items ) + 1;
foreach ( $items as $item ) {
if ( 'product_cat' == $item->object ) {
$children = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => $item->object_id,
'limit' => -1,
'orderby' => 'title',
'order' => 'ASC',
) );
if ( ! empty( $children ) && ! is_wp_error( $children ) ) {
$children_submenu = array();
foreach ( $children as $child ) {
$tmp_item = new stdClass();
$tmp_item->ID = $child->ID * 10000;
$tmp_item->post_author = $item->post_author;
$tmp_item->post_date = $child->post_date;
$tmp_item->post_date_gmt = $child->post_date_gmt;
$tmp_item->post_content = '';
$tmp_item->post_title = '';
$tmp_item->post_excerpt = '';
$tmp_item->post_status = 'publish';
$tmp_item->comment_status = $child->comment_status;
$tmp_item->ping_status = $child->ping_status;
$tmp_item->post_password = '';
$tmp_item->post_name = $child->post_name;
$tmp_item->to_ping = '';
$tmp_item->pinged = '';
$tmp_item->post_modified = $child->post_modified;
$tmp_item->post_modified_gmt = $child->post_modified_gmt;
$tmp_item->post_content_filtered = '';
$tmp_item->post_parent = 0;
$tmp_item->guid = $child->guid;
$tmp_item->menu_order = $children_order;
$tmp_item->post_type = 'nav_menu_item';
$tmp_item->post_mime_type = '';
$tmp_item->comment_count = $child->comment_count;
$tmp_item->filter = 'raw';
$tmp_item->db_id = $tmp_item->ID;
$tmp_item->menu_item_parent = $item->ID;
$tmp_item->object_id = $child->ID;
$tmp_item->object = 'product_cat';
$tmp_item->type = 'taxonomy';
$tmp_item->type_label = '';
$tmp_item->url = get_term_link( $child->term_id );
$tmp_item->title = $child->name;
$tmp_item->target = '';
$tmp_item->attr_title = '';
$tmp_item->description = '';
$tmp_item->classes = array ( 0 => '' );
$tmp_item->xfn = '';
$children_submenu[] = $tmp_item;
$children_order++;
}
$items = array_merge( $items, $children_submenu );
}
}
}
return $items;
}
}
No comments yet.