WC_AJAX::json_search_categories_tree
Search for categories and return json.
Метод класса: WC_AJAX{}
Хуки из метода
Возвращает
null. Ничего (null).
Использование
$result = WC_AJAX::json_search_categories_tree();
Код WC_AJAX::json_search_categories_tree() WC AJAX::json search categories tree WC 10.3.5
public static function json_search_categories_tree() {
ob_start();
check_ajax_referer( 'search-categories', 'security' );
if ( ! current_user_can( 'edit_products' ) ) {
wp_die( -1 );
}
$search_text = isset( $_GET['term'] ) ? wc_clean( wp_unslash( $_GET['term'] ) ) : '';
$number = isset( $_GET['number'] ) ? absint( $_GET['number'] ) : 50;
$args = array(
'taxonomy' => array( 'product_cat' ),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'number' => $number,
'name__like' => $search_text,
);
$terms = get_terms( $args );
$terms_map = array();
if ( $terms ) {
foreach ( $terms as $term ) {
$terms_map[ $term->term_id ] = $term;
if ( $term->parent ) {
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
$current_child = $term;
foreach ( $ancestors as $ancestor ) {
if ( ! isset( $terms_map[ $ancestor ] ) ) {
$ancestor_term = get_term( $ancestor, 'product_cat' );
$terms_map[ $ancestor ] = $ancestor_term;
}
if ( ! $terms_map[ $ancestor ]->children ) {
$terms_map[ $ancestor ]->children = array();
}
$item_exists = count(
array_filter(
$terms_map[ $ancestor ]->children,
function ( $term ) use ( $current_child ) {
return $term->term_id === $current_child->term_id;
}
)
) === 1;
if ( ! $item_exists ) {
$terms_map[ $ancestor ]->children[] = $current_child;
}
$current_child = $terms_map[ $ancestor ];
}
}
}
}
$parent_terms = array_filter(
array_values( $terms_map ),
function ( $term ) {
return 0 === $term->parent;
}
);
wp_send_json( apply_filters( 'woocommerce_json_search_found_categories', $parent_terms ) );
}