1. 程式人生 > >wordpress 在分類目錄為分類新增分類型別

wordpress 在分類目錄為分類新增分類型別

 // 分類新增欄位  
function add_taxonomy_field(){  
    $type = ['article' => '文章', 'product' => '產品', 'case' => '案例'];
    $html = '<div class="form-field"><label for="tag-type">型別</label>'; 
    foreach($type as $key => $val) {
        $html .= '<input name="tag-type" id="tag-type-'.$key.'" type="radio" value="'.$key.'" />' . $val; 
    }
    $html .= '</div>';     
    echo $html;   
}  
add_action('category_add_form_fields','add_taxonomy_field',10,2);  


// 分類編輯欄位  
function edit_taxonomy_field( $tag ){  
    $value =  get_option('tag-type-'.$tag->term_id);
    $type = ['article' => '文章', 'product' => '產品', 'case' => '案例'];
    $html = '<tr class="form-field form-required term-name-wrap"><th scope="row"><label for="tag-type">型別</label></th><td>'; 
    foreach($type as $key => $val) {
        if ( $value == $key ) {
            $html .= '<input name="tag-type" id="tag-type-'.$key.'" type="radio" checked="checked" value="'.$key.'" />' . $val;
        } else {
            $html .= '<input name="tag-type" id="tag-type-'.$key.'" type="radio" value="'.$key.'" />' . $val;
        }
         
    }
    $html .= '</td></tr>';        
    echo $html;
}  
add_action('category_edit_form_fields','edit_taxonomy_field',10,2);  

// 儲存資料  
function save_taxonomy_field( $term_id ){  
    if( isset($_POST['tag-type']) ){  
        //判斷許可權--可改  
        if(!current_user_can('manage_categories')){  
            return $term_id;  
        }  

        $tag_type_key = 'tag-type-'.$term_id; 
        $tag_type_value = $_POST['tag-type']; 
              
        // 更新選項值  
        update_option( $tag_type_key, $tag_type_value );   
    }  
}  

function taxonomy_setup() {
    add_action('created_category','save_taxonomy_field',10,1);  
    add_action('edited_category','save_taxonomy_field',10,1);
}

add_action( 'admin_init', 'taxonomy_setup' );