WordPress自定义分类层次插入

问题描述

我在使此循环正常工作方面遇到一些麻烦。

我想在自定义wordpress分类法中将Google地图中的国家,州,城市,社区插入为等级体系。所有变量都已设置,但是当它通过for循环运行时,只会填充并插入国家或第一个数组$ loop [0]。

我正在使用$ pastID [$ d]保存最后一个term_id,以便在下一学期中将其用作父项。如果这很糟糕,请告诉我。

在连接现有插件时,我也必须使用Globals。

    $custom_tax_name = "location";
    $loop = array();
    $loop[0] = $country = $GLOBALS['custom_array']['country'];
    $loop[1] = $state = $GLOBALS['custom_array']['state'];
    $loop[2] = $city = $GLOBALS['custom_array']['city'];
    $loop[3] = $community = $GLOBALS['custom_array']['community'];

$pastID = array();
$terms = array();

for($i = 0; $i<=3; $i++) {
    $d = $i - 1;
    if (!empty($loop[$i])){
        $term_exist = term_exists( $loop[$i],$custom_tax_name );
        if (!$term_exist){
            if ($i == 0){
            $pastID[$d] = wp_insert_term("$loop[$i]",$custom_tax_name);   
            } else {
                if (empty($pastID[$d]['term_id'])){
                    $term = get_term_by('name',$loop[$i],$custom_tax_name);
                    $termParent = $term ? $term->parent : false;
                        if ($termParent == false){
                            continue;
                        }
                    $pastID[$d] = wp_insert_term("$loop[$i]",$custom_tax_name,array("parent" => $termParent));
                } else {
                    $termParent = $pastID[$d]['term_id'];
                    $pastID[$d] = wp_insert_term("$loop[$i]",array("parent" => $termParent));
                }
            }
        } else {
            $pastID[$d] = $term_exist;
        }
        $terms[] = $loop[$i];
        delete_option('{$custom_tax_name}_children');
    } // nothing exist

}

解决方法

好的,所以我看了一下之后感觉很慢。

$ pastID在设置时需要具有$ i变量,在下一个循环中引用时需要具有$ d。下面的代码将使用我针对国家,州,城市和社区的变量创建一个深度高达4+的层次分类。它将检查该变量是否存在,如果不存在,将确保它具有一个可与其关联的父项或不将其插入。无论如何,谢谢。

for($i = 0; $i<=3; $i++) {
    $d = $i - 1;
    if (!empty($loop[$i])){
        $term_exist = term_exists( $loop[$i],$custom_tax_name );
        if (!$term_exist){
            if ($i == 0){
            $pastID[$i] = wp_insert_term($loop[$i],$custom_tax_name);   
            } else {
                if (empty($pastID[$d]['term_id'])){
                    $term = get_term_by('name',$loop[$i],$custom_tax_name);
                    $termParent = $term ? $term->parent : false;
                        if ($termParent == false){
                            continue;
                        }
                    $pastID[$i] = wp_insert_term($loop[$i],$custom_tax_name,array("parent" => $termParent));
                } else {
                    $termParent = $pastID[$d]['term_id'];
                    $pastID[$i] = wp_insert_term("$loop[$i]",array("parent" => $termParent));
                }
            }
        } else {
            $pastID[$d] = $term_exist;
        }
        $terms[] = $loop[$i];
        delete_option('{$custom_tax_name}_children');
    } // nothing exist

}