2017.10.31WEB - WordPress

カテゴリー編集部分に独自のフィールド設置

投稿の場合

functions.phpへ

<?php
add_action('edit_category_form_fields', 'extra_category_fields'); //編集画面
add_action('category_add_form_fields', 'extra_category_fields');  //新規追加画面

function extra_category_fields($tag) {
  $t_id = $tag->term_id;
  $cat_meta = get_option("cat_$t_id");
?>
<tr class="form-field">
  <th><label for="pagetitle">項目名</label></th>
  <td><input type="text" name="cat_meta[mytext]" id="mytext" size="25" value="<?php if(isset($cat_meta['mytext'])) echo esc_html($cat_meta['mytext']) ?>" /></td>
</tr>
<?php
}
?>

カスタム投稿の場合

functions.phpへ

<?php
add_action('投稿タイプ(タクソノミー)_cat_edit_form_fields', 'extra_taxonomy_fields'); //編集画面
add_action('投稿タイプ(タクソノミー)_cat_add_form_fields', 'extra_taxonomy_fields');  //新規追加画面

function extra_taxonomy_fields( $tag ) {
  $t_id = $tag->term_id;
  $cat_meta = get_option("cat_$t_id");
?>
<tr class="form-field">
  <th><label for="pagetitle">項目名</label></th>
  <td><input type="text" name="cat_meta[mytext]" id="mytext" size="25" value="<?php if(isset($cat_meta['mytext'])) echo esc_html($cat_meta['mytext']) ?>" /></td>
</tr>
<?php
}
?>

登録する

functions.phpへ

<?php
add_action ('edited_term', 'save_extra_category_fileds');
function save_extra_category_fileds($term_id) {
  if(isset($_POST['cat_meta'])) {
    $t_id = $term_id;
    $cat_meta = get_option("cat_$t_id");
    $cat_keys = array_keys($_POST['cat_meta']);
    foreach ($cat_keys as $key){
      if (isset($_POST['cat_meta'][$key])){
        $cat_meta[$key] = $_POST['cat_meta'][$key];
      }
    }
    update_option("cat_$t_id", $cat_meta);
  }
}
?>

テンプレートからの呼び出し

<?php
/* 投稿の場合 */
$thiscat = get_category($cat);
$cat_data = get_option('cat_'.intval($thiscat->term_id));
$mytext = $cat_data['mytext'];

/* カスタム投稿の場合 */
$thiscat = get_queried_object();
$t_id = $thiscat->term_id;
$cat_meta = get_option("cat_$t_id");
$mytext = $cat_meta['mytext'];
?>