本篇文章更新時間:2023/10/18
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣 或 新台幣 贊助支持。
客戶整理了一大張產品的分類表,滿滿的階層結構就算了,資料量也不小。
如果要手動建立也是要花不少時間,想把這些資料整理成一個巢狀的階層陣列來匯入。
結果圖如下:
使用的陣列如下:
$categories = [
[
'Category 1' => [
'Subcategory 1.1' => [
'Subcategory 1.1.1',
'Subcategory 1.1.2',
],
'Subcategory 1.2' => [
'Subcategory 1.2.1',
'Subcategory 1.2.2' => [
'1.2.2.1',
'1.2.2.2' => [
'1.2.2.2.1',
'1.2.2.2.2',
'1.2.2.2.3' => [
'1.2.2.2.3.1',
'1.2.2.2.3.2',
'1.2.2.2.3.3',
],
],
],
],
],
],
[
'Category 2' => [
'Subcategory 2.1',
'Subcategory 2.2' => [
'Subcategory 2.2.1' => [
'Subcategory 2.2.1.1' => [
'2.2.1.1.1',
'2.2.1.1.2',
],
],
],
],
],
];
使用的方法如下:
function create_wp_categories_by_nested_array($categories, $taxonomy = 'category', $parent_id = 0) {
foreach ($categories as $category_name => $sub_category) {
$term = '';
if (!is_numeric($category_name)) {
print_r('1: ');
print_r($category_name);
// 確認 term 是否已存在
$check_term_exists = term_exists($category_name, $taxonomy);
if ($check_term_exists) {
$term = get_term_by('name', $category_name, $taxonomy, ARRAY_A);
print_r(' 已存在!略過不建立。' . PHP_EOL);
} else {
// 不存在,建立!
$new_term = wp_insert_term($category_name, $taxonomy, ['parent' => $parent_id]);
// wp_insert_term(
// 'Apple', // the term
// 'product', // the taxonomy
// array(
// 'description' => 'A yummy apple.',
// 'slug' => 'apple',
// 'parent' => $parent_term_id,
// )
// );
if (!is_wp_error($new_term)) {
$term = $new_term;
print_r(' 不存在!建立:' . $term['term_id'] . PHP_EOL);
} else {
print_r(' 不存在!建立失敗。' . PHP_EOL);
}
}
}
if (is_numeric($category_name) && !is_array($sub_category)) {
print_r('2: ');
print_r($sub_category);
$check_term_exists = term_exists($sub_category, $taxonomy);
if ($check_term_exists) {
$term = get_term_by('name', $sub_category, $taxonomy, ARRAY_A);
print_r(' 已存在!略過不建立。' . PHP_EOL);
} else {
// 不存在,建立!
$new_term = wp_insert_term($sub_category, $taxonomy, ['parent' => $parent_id]);
if (!is_wp_error($new_term)) {
$term = $new_term;
print_r(' 不存在!建立:' . $term['term_id'] . PHP_EOL);
} else {
print_r(' 不存在!建立失敗。' . PHP_EOL);
}
}
}
if (is_array($sub_category)) {
print_r('3: ');
$parent_id = isset($term['term_id']) ? $term['term_id'] : 0;
print_r('上層分類編號:' . $parent_id . PHP_EOL);
create_wp_categories_by_nested_array($sub_category, $taxonomy, $parent_id);
continue;
}
}
}
第一個參數是陣列的輸入值,第二個參數預設是內建的 taxonomy「分類」(category
)如有要其他客製化 taxonomy 的話帶入設定名稱即可,最後就是當前設定分類的上層分類編號(基本上是不用去設定第三個參數)。
設計這方法,以後整理好客戶要建立的階層分類直接帶入,不管幾層都可以,省時省力啊!