0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WordPress 便利function集

Last updated at Posted at 2022-10-21

// コレクションの重複を削除

function collection_uniq($collection) {
  $keys = $collection;
  for ($i = 0; $i < $N; $i++) {
    $key = 'KEY' . mt_rand(1, $R);
    if (!in_array($key, $keys)) {
      $keys[] = $key;
    }
  }
  return $keys;
}

// 配列をフラットにする

function array_flatten(array $arr) {
  $ret = array();

  foreach ($arr as $item) {
    if (is_array($item)) {
      $ret = array_merge($ret, array_flatten($item));
    } else {
      $ret[] = $item;
    }
  }

  return $ret;
}

// 明確なテンプレートが存在しない場合に親のテンプレートを使用する。

function my_category_template( $template ) {
	$category = get_queried_object();
	if ( $category->parent != 0 &&
		( $template == "" || strpos( $template, "category.php" ) !== false ) ) {
		$templates = array();
		while ( $category->parent ) {
			$category = get_category( $category->parent );
			if ( !isset( $category->slug ) ) break;
			$templates[] = "category-{$category->slug}.php";
			$templates[] = "category-{$category->term_id}.php";
		}
		$templates[] = "category.php";
		$template = locate_template( $templates );
	}
	return $template;
}
add_filter( 'category_template', 'my_category_template' );

// 投稿のタグ表示をカテゴリライクのスタイルに変更する。

function re_register_post_tag_taxonomy() {
  global $wp_rewrite;
  $rewrite = array(
    'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
    'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
    'ep_mask' => EP_TAGS,
  );

  $labels = array(
    'name' => _x( 'Tags', 'taxonomy general name' ),
    'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
    'search_items' => __( 'Search Tags' ),
    'popular_items' => __( 'Popular Tags' ),
    'all_items' => __( 'All Tags' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Tag' ),
    'view_item' => __( 'View Tag' ),
    'update_item' => __( 'Update Tag' ),
    'add_new_item' => __( 'Add New Tag' ),
    'new_item_name' => __( 'New Tag Name' ),
    'separate_items_with_commas' => __( 'Separate tags with commas' ),
    'add_or_remove_items' => __( 'Add or remove tags' ),
    'choose_from_most_used' => __( 'Choose from the most used tags' ),
    'not_found' => __( 'No tags found.' )
  );

  register_taxonomy( 'post_tag', 'post', array(
    'hierarchical' => true,
    'query_var' => 'tag',
    'rewrite' => $rewrite,
    'public' => true,
    'show_ui' => true,
    'show_admin_column' => true,
    '_builtin' => true,
    'labels' => $labels
  ) );
}
add_action( 'init', 're_register_post_tag_taxonomy', 1 );

// タグ別記事一覧を取得

function get_tag_posts($tag, $page) {
  $args = array(
    'tag__in'        => $tag->term_id,
    'posts_per_page' => $page,
    'post_status' => 'publish',
  );
  $tag_posts = new WP_Query( $args );
  return $tag_posts->posts;
}

// 記事のサブカテゴリ一覧を取得

function get_post_subcategories( $post_id ) {
  $sub_categories = array();
  $categories = get_the_category($post_id);
  foreach ($categories as $key => $category) {
    if ($category->parent) {
      $sub_categories[$key] = $category;
    }
  }
  return $sub_categories;
}

// WordPress ContactForm7 動的なオリジナルのフォームタグ

// Contact Form 7 が導入されていて wpcf7_add_form_tag が有効な場合のみ
if( function_exists('wpcf7_add_form_tag') ) {
  // ※タグを出力するfunctionを先に記述していないと上手く動作しない
  function make_talent_select_tag($tag) {
    // 基本的な設定は参考にするタグの出力の仕方を参考に
    $t = new WPCF7_Shortcode($tag);
    $atts = array();
    $class = wpcf7_form_controls_class( $tag->type );
    $atts['class'] = $tag->get_class_option( $class );
    $atts['id'] = $tag->get_id_option();
    $atts['name'] = $tag->name;
    $name = sanitize_html_class( $atts['name'] );

    if ( $tag->is_required() ) {
      $atts['aria-required'] = 'true';
    }

    $atts['aria-invalid'] = $validation_error ? 'true' : 'false';

    // デフォルト選択 selected:値 というオプションがあれば該当するoptionタグを selected にする
    $default = $tag->get_option( 'selected', '', true );

    // first_as_label オプションで先頭を未選択状態の文字を表示できるようにする
    $first_as_label = $tag->has_option( 'first_as_label' );
    $values = $tag->values;

    $options = '';
    if( $first_as_label && count($values)) {
      $options = '<option value>' . esc_html($values[0]) . '</option>';
    }

    // タレント名一覧を取得してセレクトタグのオプションにする
    $talents = get_talent_name_list();
    foreach($talents as $val) {
      $value = esc_attr($val);
      $selected = "";
      // デフォルト選択に該当している場合 selected 属性を出力する
      if( $default == $value) {
        $selected = ' selected="selected"';
      }
      $options .= '<option value="' . $value . '"' . $selected . '>' . esc_html($val) . '</option>';
    }

    $atts = wpcf7_format_atts( $atts );
    $html = sprintf(
      '<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select></span>',
      $name, $atts, $options
    );

    // 出力するタグのHTMLを返す
    return $html;
  }

  // ショートコードなどを登録
  wpcf7_add_form_tag(array('select_talent_list', 'select_talent_list*'),
    'make_talent_select_tag',
    array(
      'name-attr' => true,
      'selectable-values' => true,
    )
  );

  // バリデーションは 元の select のものを利用
  add_filter( 'wpcf7_validate_select_talent_list', 'wpcf7_select_validation_filter', 10, 2 );
  add_filter( 'wpcf7_validate_select_talent_list*', 'wpcf7_select_validation_filter', 10, 2 );
}

// カスタム投稿タイプ `talent` のタイトル(名前)を返す
function get_talent_name_list() {
  $data = array();
  $args = array(
    'post_type'      => 'requirements',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'orderby'        => array(
      'menu_order' => 'DESC',
      'date' => 'ASC',
    ),
  );
  $the_query = new WP_Query($args);
  if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
      $the_query->the_post();
      $talentName = get_the_title();
      $data[] = $talentName;
    }
  }
  // reset query
  wp_reset_postdata();
  return $data;
}

// カスタムフィールドの内容をカラムに追加する

// 「商品タイプ」カラムを追加する
function manage_posts_columns($columns) {
	$columns['type'] = '商品タイプ';
    return $columns;
}
add_filter( 'manage_edit-products_columns', 'manage_posts_columns' );

// カスタムフィールドの内容を表示
function add_column($column_name, $post_id) {
    if( $column_name == 'type' ) {
        $stitle = get_post_meta($post_id, 'type', true);
    }
    if ( isset($stitle) && $stitle ) {
        echo attribute_escape($stitle);
    } else {
        echo __('None');
    }
}
add_action( 'manage_posts_custom_column', 'add_column', 10, 2 );

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?