WordPressで使用する、functions.phpのテンプレート1
WordPressのfunctions.phpの中身について、どのようなサイトを作るかにより変わるとは思いますが、あると便利なものをまとめてみました。ご参考ください。
画像関連
アップロードした画像の圧縮率を変更
function jpeg_quality_callback($arg){ return (int)100; } add_filter('jpeg_quality', 'jpeg_quality_callback');
サムネイルを利用可能
add_theme_support( 'post-thumbnails', array( 'post', /*カスタム投稿タイプを登録*/ ) );
画像サイズを追加
add_image_size('sSquareThumb', '300', '300', true);
カスタム投稿タイプ
function add_sample_post_type() { $jName = 'サンプル'; $params = array( 'labels' => array( //管理画面のサイドバーに表示させる名前 'name' => $jName, //日本語は基本単複共通なので、上と同じで良い。 'singular_name' => $jName, 'add_new' => '新規追加', 'add_new_item' => '新規追加', 'edit_item' => '編集する', 'new_item' => '新規', 'all_items' => '一覧', 'view_item' => '見る', 'search_items' => '検索する', 'not_found' => '見つかりませんでした。', 'not_found_in_trash' => 'ゴミ箱内に見つかりませんでした。' ), 'public' => true, //アーカイブが必要でない時は、ここをfalseにすること 'has_archive' => true, /****************************** 以下、この投稿タイプに付ける機能を決める。追加できる機能は以下の通り。 'title' (タイトル) 'editor' (内容の編集) 'author' (作成者) 'thumbnail' (アイキャッチ画像。現在のテーマが post-thumbnails をサポートしていること) 'excerpt' (抜粋) 'trackbacks' (トラックバック送信) 'custom-fields' (カスタムフィールド) 'comments' (コメントの他、編集画面にコメント数のバルーンを表示する) 'revisions' (リビジョンを保存する) 'page-attributes' (メニューの順序。「親〜」オプションを表示するために hierarchical が true であること) 'post-formats' (投稿のフォーマットを追加。投稿フォーマットを参照) (抜粋)関数リファレンス/register post type - WordPress Codex 日本語版 http://wpdocs.sourceforge.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/register_post_type ******************************/ 'supports' => array( 'title', ), ); register_post_type( 'sample', $params ); } add_action( 'init', 'add_sample_post_type' );
カスタム分類(カスタムタクソノミ―)
カスタム分類(カスタムタクソノミー)を追加
function create_sampleocat_taxonomies() { $jName = 'サンプル種類'; // ラベルを作成 $labels = array( //管理画面のサイドバーに表示させる名前 'name' => $jName, //日本語は基本単複共通なので、上と同じで良い。 'singular_name' => $jName, 'search_items' => '検索', 'all_items' => '全て', 'parent_item' => '親', 'parent_item_colon' => '親:', 'edit_item' => '編集', 'update_item' => '更新', 'add_new_item' => '新規追加', 'new_item_name' => '新規', 'menu_name' => $jName ); $args = array( // タクソノミーの項目に親子関係を付ける場合、true 'hierarchical' => true, 'labels' => $labels, // ここに仕掛けをすることで、記事パーマリンクの中にタクソノミーのslugを追加できるようにすることもできます。 'rewrite' => array( 'slug' => 'samplecat' ) ); // 使用するカスタム投稿タイプを設定します。 register_taxonomy( 'samplecat', array( 'sample' ), $args ); } add_action( 'init', 'create_samplecat_taxonomies' );
カスタム分類の未選択時にデフォルトを設定
//「society」カスタム投稿タイプ、「other」カスタム分類の例 function add_defaultcategory_automatically($post_ID) { global $wpdb; $customTax = 'society'; $defaultTermSlug = 'other'; $curTerm = wp_get_object_terms($post_ID, $customTax); if (0 == count($curTerm)): $termObj = get_term_by('slug', $defaultTermSlug, $customTax); $defaultTerm= array($termObj->term_id); wp_set_object_terms($post_ID, $defaultTerm, $customTax); endif; } add_action('publish_ectdinfo', 'add_defaultcategory_automatically');
管理画面系カスタマイズ
カスタム投稿タイプの管理画面でカスタム分類のドロップダウン絞り込み機能を追加
function customtax_restrict_manage_posts() { global $typenow; $args=array( 'public' => true, '_builtin' => false ); $post_types = get_post_types($args); if ( in_array($typenow, $post_types) ): $filters = get_object_taxonomies($typenow); foreach ($filters as $tax_slug): tax_obj = get_taxonomy($tax_slug); wp_dropdown_categories(array( 'show_option_all' => __('Show All '.$tax_obj->label ), 'taxonomy' => $tax_slug, 'name' => $tax_obj->name, 'orderby' => 'term_order', 'selected' => $_GET[$tax_obj->query_var], 'hierarchical' => $tax_obj->hierarchical, 'show_count' => false, 'hide_empty' => true )); endforeach; endif; } function customtax_convert_restrict($query) { global $pagenow; global $typenow; if ($pagenow=='edit.php'): $filters = get_object_taxonomies($typenow); foreach ($filters as $tax_slug) : $var = &$query->query_vars[$tax_slug]; if ( isset($var) && $var>0): $term = get_term_by('id',$var,$tax_slug); $var = $term->slug; endif; endforeach; endif; return $query; } add_action( 'restrict_manage_posts', 'customtax_restrict_manage_posts' ); add_filter('parse_query','customtax_convert_restrict');
投稿一覧画面で、カスタム分類のドロップダウン絞り込み機能を追加
//「authorType」カスタム分類の例 function add_post_taxonomy_restrict_filter() { global $post_type; if ( 'post' == $post_type ) : //ここで、selectタグのname属性値は、「小文字」にする事 ?> <select name="authortype"> <option value="">カテゴリー指定なし</option> <?php $terms = get_terms('authorType'); foreach ($terms as $term) : ?> <option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option> <?php endforeach; ?> </select> <?php endif; } add_action( 'restrict_manage_posts', 'add_post_taxonomy_restrict_filter' );
投稿・カスタム投稿一覧画面で独自のカラムを追加
function customize_admin_manage_posts_columns($columns) { //投稿タイプごとに表示させるカラムを追加 if('shop' == get_post_type()): $columns['thumbnail'] = 'サムネイル'; $columns['shop_area'] = 'エリア'; endif; return $columns; } //投稿タイプ=>カラムごとに表示させるデータを設定する function customize_admin_add_column($column_name, $post_id) { if(in_array(get_post_type(), array('shop'))): if ( 'thumbnail' == $column_name): //サムネイル画像取得 $thum = get_the_post_thumbnail($post_id, 'img100x100', array( 'style'=>'width:75px;height:auto;' )); echo $thum endif; if( 'shop_area' == $column_name )): //areaカスタムタクソノミーを表示させる $terms = get_the_terms( $post_id, 'area' ); $cnt = 0; foreach($terms as $var) : echo $cnt != 0 ? ", " : ""; echo "<a href=\"" . get_admin_url() . "edit.php?philo-type=" . $var->slug . "&post_type=philosophy" . "\">" . $var->name . "</a>"; ++$cnt; endforeach; endif; endif; } add_filter( 'manage_posts_columns', 'customize_admin_manage_posts_columns' ); add_action( 'manage_posts_custom_column', 'customize_admin_add_column', 10, 2 ); //投稿タイプごとに表示させるカラム順番を設定 function sort_shop_column($columns){ $columns = array( 'cb' => '<input type="checkbox" />', 'thumbnail' => 'サムネイル', 'title' => 'タイトル', 'shop_area' => 'エリア', 'author' => '作成者', 'date' => '日時', ); //もし、表示させたくないカラムがある場合、/unsetを利用する //unset($columns['date'],$columns['author'],......); return $columns; } add_filter( 'manage_shop_posts_columns', 'sort_shop_column');
クイック編集にカスタムフィールドを表示・編集可能にする
ログイン画面系カスタマイズ
パーマリンク系カスタマイズ
パーマリンクを書き換える
//例:特定の投稿タイプでパーマリンクの形を変更する function rewrite_posttype_permalink($permalink, $post_id, $leavename) { $post = get_post($post_id); //パーマリンクを書き換えたい目的の投稿タイプを指定 $postType = 'society'; //もし、開いている管理画面記事一覧の投稿タイプが目的のものと違う場合、通常のパーマリンク if (strpos($permalink, $postType) === FALSE) return $permalink; //目的の投稿タイプの場合、書き換えたパーマリンクの値を返す //ここでは、日付をパーマリンク内に挿入させている $dateAll = explode(' ', $post->post_date); $yearMonthDay = explode("-", $dateAll[0]); return str_replace("/{$postType}", "/{$postType}/{$yearMonthDay[0]}/{$yearMonthDay[1]}/{$yearMonthDay[2]}", $permalink); } add_filter('post_link', 'rewrite_posttype_permalink', 10, 3); add_filter('post_type_link', 'rewrite_posttype_permalink', 10, 3);
リライトルール系カスタマイズ
リライトルール周りについては、別途作成予定ですが、よく使う「カスタム投稿タイプでアーカイブ」の設定例を挙げておきます。
//例:カスタム投稿タイプのアーカイブ形式のパーマリンクを設定 function extra_add_rewrite_rules( $wpRewrite ) { //この関数は、下のカスタム関数参照 $postTypes = custom_post_types_array(); $newRules = array(); foreach($postTypes as $key): $newRules += array( //以下、アーカイブを設定 '(' . $key . ')/([0-9]{4})/([0-9]{1,2})' => 'index.php?post_type=' . $key . '&year=' . $wpRewrite->preg_index(2) . '&monthnum=' . $wpRewrite->preg_index(3), '(' . $key . ')/([0-9]{4})' => 'index.php?post_type=' . $key . '&year=' . $wpRewrite->preg_index(2), //以下、投稿タイプ個別記事表示の設定 '(' . $key . ')/(.*)' => 'index.php?post_type=' . $key . '&name=' . $wpRewrite->preg_index(2), ); endforeach; $wpRewrite->rules = $newRules + $wpRewrite->rules; } add_action('generate_rewrite_rules', 'extra_add_rewrite_rules');
カスタム関数
カスタム投稿タイプ一覧を配列で返す
function custom_post_types_array($public = true){ $args = array( 'public' => $public, '_builtin' => false ); $postTypes = get_post_types($args); $postTypesArray = array(); foreach($postTypes as $key): array_push($postTypesArray, $key); endforeach; return $postTypesArray; }
エスケープ用関数
function hesc($text){ return htmlspecialchars($text, ENT_QUOTES); }
テンプレートディレクトリを返す関数
//なくてもいいが、子テーマでget_template_directory _uri()は、親テーマのディレクトリを返してしまうので、これを使って、対応する。 function tempDir(){ return get_template_directory_uri(); }
既存の関数のカスタマイズ
カスタム投稿タイプ用カレンダー
function get_cpt_calendar($cpt,$initial = true, $echo = true) { global $wpdb, $m, $monthnum, $year, $wp_locale, $posts; $cache = array(); $key = md5( $m . $monthnum . $year ); if ( $cache = wp_cache_get( 'get_calendar', 'calendar' ) ) { if ( is_array($cache) && isset( $cache[ $key ] ) ) { if ( $echo ) { echo apply_filters( 'get_calendar', $cache[$key] ); return; } else { return apply_filters( 'get_calendar', $cache[$key] ); } } } if ( !is_array($cache) ) $cache = array(); // 指定されたカスタム投稿タイプに投稿があるかチェック if ( !$posts ) { $gotsome = $wpdb->get_var("SELECT 1 as test FROM $wpdb->posts WHERE post_type = '$cpt' AND post_status = 'publish' LIMIT 1"); // 指定されたカスタム投稿タイプの投稿が無ければ、キャッシュID get_calenderに、$cache[$key]要素(空)を追加した、$cacheデータを保存 if ( !$gotsome ) { $cache[ $key ] = ''; wp_cache_set( 'get_calendar', $cache, 'calendar' ); return; } } if ( isset($_GET['w']) ) $w = ''.intval($_GET['w']); // 検索する月日を設定 $week_begins = intval(get_option('start_of_week')); if ( !empty($monthnum) && !empty($year) ) { $thismonth = ''.zeroise(intval($monthnum), 2); $thisyear = ''.intval($year); } elseif ( !empty($w) ) { $thisyear = ''.intval(substr($m, 0, 4)); $d = (($w - 1) * 7) + 6; $thismonth = $wpdb->get_var("SELECT DATE_FORMAT((DATE_ADD('{$thisyear}0101', INTERVAL $d DAY) ), '%m')"); } elseif ( !empty($m) ) { $thisyear = ''.intval(substr($m, 0, 4)); if ( strlen($m) < 6 ) $thismonth = '01'; else $thismonth = ''.zeroise(intval(substr($m, 4, 2)), 2); } else { $thisyear = gmdate('Y', current_time('timestamp')); $thismonth = gmdate('m', current_time('timestamp')); } $unixmonth = mktime(0, 0 , 0, $thismonth, 1, $thisyear); $last_day = date('t', $unixmonth); // 前の月のデータを取得する $previous = $wpdb->get_row(" SELECT MONTH(post_date) AS month, YEAR(post_date) AS year FROM $wpdb->posts WHERE post_date < '$thisyear-$thismonth-01' AND post_type = '$cpt' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1 "); //翌月のデータを取得する $next = $wpdb->get_row(" SELECT MONTH(post_date) AS month, YEAR(post_date) AS year FROM $wpdb->posts WHERE post_date > '$thisyear-$thismonth-{$last_day} 23:59:59' AND post_type = '$cpt' AND post_status = 'publish' ORDER BY post_date ASC LIMIT 1 "); /* キャプション設定 */ $calendar_caption = _x('%1$s %2$s', 'calendar caption'); $calendar_output = '<table id="wp-calendar"> <caption>' . sprintf($calendar_caption, $wp_locale->get_month($thismonth), date('Y', $unixmonth)) . '</caption> <thead> <tr>'; $myweek = array(); for ( $wdcount=0; $wdcount<=6; $wdcount++ ) { $myweek[] = $wp_locale->get_weekday(($wdcount+$week_begins)%7); } foreach ( $myweek as $wd ) { $day_name = (true == $initial) ? $wp_locale->get_weekday_initial($wd) : $wp_locale->get_weekday_abbrev($wd); $wd = esc_attr($wd); $calendar_output .= "\n\t\t<th scope=\"col\" title=\"$wd\">$day_name</th>"; } $calendar_output .= ' </tr> </thead> <tfoot> <tr>'; //前の月にデータが有る場合 if ( $previous ) { $calendar_output .= "\n\t\t".'<td colspan="3" id="prev"><a href="' . get_month_link($previous->year, $previous->month) . '?post_type='.$cpt.'" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s'), $wp_locale->get_month($previous->month), date('Y', mktime(0, 0 , 0, $previous->month, 1, $previous->year)))) . '">« ' . $wp_locale->get_month_abbrev($wp_locale->get_month($previous->month)) . '</a></td>'; } else { $calendar_output .= "\n\t\t".'<td colspan="3" id="prev" class="pad"> </td>'; } $calendar_output .= "\n\t\t".'<td class="pad"> </td>'; //次の月にデータが有る場合 if ( $next ) { $calendar_output .= "\n\t\t".'<td colspan="3" id="next"><a href="' . get_month_link($next->year, $next->month) . '?post_type='.$cpt.'" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s'), $wp_locale->get_month($next->month), date('Y', mktime(0, 0 , 0, $next->month, 1, $next->year))) ) . '">' . $wp_locale->get_month_abbrev($wp_locale->get_month($next->month)) . ' »</a></td>'; } else { $calendar_output .= "\n\t\t".'<td colspan="3" id="next" class="pad"> </td>'; } $calendar_output .= ' </tr> </tfoot> <tbody> <tr>'; // 当月分の投稿データを取得 $dayswithposts = $wpdb->get_results(" SELECT DISTINCT DAYOFMONTH(post_date) FROM $wpdb->posts WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' AND post_type = '$cpt' AND post_status = 'publish' AND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' ", ARRAY_N); //当月分のデータがある場合 //その日付だけを $daywithpost配列に入れる if ( $dayswithposts ) { foreach ( (array) $dayswithposts as $daywith ) { $daywithpost[] = $daywith[0]; } } else { $daywithpost = array(); } //同様に記事タイトルを$ak_titles_for_day配列に入れる if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'camino') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) $ak_title_separator = "\n"; else $ak_title_separator = ', '; $ak_titles_for_day = array(); $ak_post_titles = $wpdb->get_results(" SELECT ID, post_title, DAYOFMONTH(post_date) as dom " ."FROM $wpdb->posts " ."WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' " ."AND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' " ."AND post_type = '$cpt' AND post_status = 'publish'" ); if ( $ak_post_titles ) { foreach ( (array) $ak_post_titles as $ak_post_title ) { $post_title = esc_attr( apply_filters( 'the_title', $ak_post_title->post_title, $ak_post_title->ID ) ); if ( empty($ak_titles_for_day['day_'.$ak_post_title->dom]) ) $ak_titles_for_day['day_'.$ak_post_title->dom] = ''; if ( empty($ak_titles_for_day["$ak_post_title->dom"]) ) // first one $ak_titles_for_day["$ak_post_title->dom"] = $post_title; else $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title; } } // See how much we should pad in the beginning $pad = calendar_week_mod(date('w', $unixmonth)-$week_begins); if ( 0 != $pad ) $calendar_output .= "\n\t\t".'<td colspan="'. esc_attr($pad) .'" class="pad"> </td>'; $daysinmonth = intval(date('t', $unixmonth)); for ( $day = 1; $day <= $daysinmonth; ++$day ) { if ( isset($newrow) && $newrow ) $calendar_output .= "\n\t</tr>\n\t<tr>\n\t\t"; $newrow = false; if ( $day == gmdate('j', current_time('timestamp')) && $thismonth == gmdate('m', current_time('timestamp')) && $thisyear == gmdate('Y', current_time('timestamp')) ) $calendar_output .= '<td id="today">'; else $calendar_output .= '<td>'; if ( in_array($day, $daywithpost) ) // any posts today? $calendar_output .= '<a href="' . get_day_link( $thisyear, $thismonth, $day ) . '?post_type='.$cpt.'" title="' . esc_attr( $ak_titles_for_day[ $day ] ) . "\">$day</a>"; else $calendar_output .= $day; $calendar_output .= '</td>'; if ( 6 == calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins) ) $newrow = true; } $pad = 7 - calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins); if ( $pad != 0 && $pad != 7 ) $calendar_output .= "\n\t\t".'<td class="pad" colspan="'. esc_attr($pad) .'"> </td>'; $calendar_output .= "\n\t</tr>\n\t</tbody>\n\t</table>"; $cache[ $key ] = $calendar_output; wp_cache_set( 'get_calendar', $cache, 'calendar' ); if ( $echo ) echo apply_filters( 'get_calendar', $calendar_output ); else return apply_filters( 'get_calendar', $calendar_output ); }
カスタム投稿タイプ用の月別アーカイブ作成(wp_get_archivesのカスタマイズ)
function customPost_getarchives_where( $where, $r ) { $myPostType = get_post_type(); $where = str_replace( '\'post\'', '\'' . $myPostType . '\'' , $where ); return $where; } function customPost_get_archives_link($linkHtml) { $repBlogUrl = str_replace(array(':', '/', '.'), array('\:', '\/', '\.'), get_bloginfo('url')); $addLink = get_post_type(); $linkHtml = preg_replace("/href='(" . $repBlogUrl . ")\/([0-9]{4}\/[0-9]{1,2}\/)'/", "href='$1/" . $addLink . "/$2'", $linkHtml); return $linkHtml; } add_filter( 'getarchives_where', 'customPost_getarchives_where', 10, 2 ); add_filter( 'get_archives_link', 'customPost_get_archives_link' ); wp_get_archives(); remove_filter( 'getarchives_where', 'customPost_getarchives_where', 10, 2 ); remove_filter( 'get_archives_link', 'customPost_get_archives_link' );
カテゴリーを指定した月別アーカイブのカスタマイズ(wp_get_archivesのカスタマイズ)
function my_getarchives_category_where($where, $args){ global $wpdb; if (isset($args['cat'])){ // 引数にcatと名前の付いた変数がカンマ区切りでセットされている場合、それぞれの数字を分割して配列$selectedCategoriesに格納する $selectedCategories = explode(',',$args['cat']); //それぞれの配列の数字が、負の場合=>$categoriesOutに、正の場合=>$categoriesInに、カンマ区切りで付け加える。 foreach ($selectedCategories as $key) { if($key<0){ $categoriesOut .= abs($key).","; }else{ $categoriesIn .= abs($key).","; } } //それぞれの変数の最後の,文字を削除 $categoriesIn = rtrim($categoriesIn,","); $categoriesOut = rtrim($categoriesOut,","); //$whereでSQLのwhere句を作成する。 $where .= ' AND '.$wpdb->prefix.'posts.ID IN (SELECT DISTINCT ID FROM '.$wpdb->prefix.'posts' .' JOIN '.$wpdb->prefix.'term_relationships term_relationships ON term_relationships.object_id = '.$wpdb->prefix.'posts.ID' .' JOIN '.$wpdb->prefix.'term_taxonomy term_taxonomy ON term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id' .' WHERE term_taxonomy.taxonomy = \'category\''; if (!empty($categoriesIn)) { $where .= " AND term_taxonomy.term_id IN ($categoriesIn)"; } if (!empty($categoriesOut)) { $where .= " AND term_taxonomy.term_id NOT IN ($categoriesOut)"; } $where .= ')'; } return $where; } add_filter( 'getarchives_where', 'my_getarchives_category_where', 10, 2 ); wp_get_archives('cat=7,-2,3,4); remove_filter( 'get_archives_link', 'customPost_get_archives_link' );
プラグインカスタマイズ
Contact Form 7 でメール確認用のバリデーションチェック
function wpcf7_text_validation_filter_extend( $result, $tag ) { $type = $tag['type']; $name = $tag['name']; $_POST[$name] = trim( strtr( (string) $_POST[$name], "\n", " " ) ); if ( 'email' == $type || 'email*' == $type ) : if (preg_match('/(.*)_confirm$/', $name, $matches)): $target_name = $matches[1]; if ($_POST[$name] != $_POST[$target_name]) : $result['valid'] = false; $result['reason'][$name] = '確認用のメールアドレスが一致していません'; endif; endif; endif; return $result; } add_filter( 'wpcf7_validate_email', 'wpcf7_text_validation_filter_extend', 11, 2 ); add_filter( 'wpcf7_validate_email*', 'wpcf7_text_validation_filter_extend', 11, 2 );
その他
特殊文字自動変換の停止
元のテキスト | 変換されたテキスト | シンボル名 |
---|---|---|
"---" | "—" | em ダッシュ |
" -- " | "—" | em ダッシュ |
"--" | "–" | en ダッシュ |
" - " | "–" | en ダッシュ |
"..." | "…" |
省略記号 |
WordPressが持っている、この手の変換機能を停止させます。
add_filter( 'run_wptexturize', '__return_false' );