wordpressでfunctions.phpに記述しておくと便利な機能まとめ

公開日:  最終更新日:2014/09/12

wordpressはそのまま使っても高機能で使いやいCMSですが、自己流にカスマイズすることでさらに機能的になります。

例えば、管理サイトが多くなってきて管理画面にもファビコンを付けたいとか、レスポンシブでサイトを構築した場合はサムネイル画像のwidthとheightを削除したい場合もあります。

管理画面にファビコンをつける

1// 管理画面へのファビコン
2function admin_favicon() {
3    echo '<link rel="shortcut icon" type="image/x-icon" href="'.get_bloginfo('template_url').'/images/favicon.ico" />';
4}
5add_action('admin_head', 'admin_favicon');

※このケースでは、予め使用中テーマのimagesフォルダ内にfavicon.icoを入れておく必要があります。

コメントのHTML表記とメール、ウェブサイト入力欄、「メールアドレスが公開~」を削除

1/ コメントのHTMLタグ表示を消す
2function my_special_comment_after($args){
3    $args['comment_notes_after'] = '';
4return $args;
5}
6add_filter("comment_form_defaults","my_special_comment_after");
7 
8// コメントからEmailとウェブサイトを削除
9function my_comment_form_remove($arg) {
10    $arg['url'] = '';
11    $arg['email'] = '';
12    return $arg;
13}
14add_filter('comment_form_default_fields', 'my_comment_form_remove');
15 
16// コメントから「メールアドレスが公開されることはありません」を削除
17function my_comment_form_before( $defaults){
18    $defaults['comment_notes_before'] = '';
19    return $defaults;
20}
21add_filter( "comment_form_defaults", "my_comment_form_before");

※設定→ディスカッションから「」のチェックを外すしておく

画像からwidthとheightを削除する

1// 画像からwidthとheightを削除
2add_filter( 'post_thumbnail_html', 'remove_width_and_height_attribute', 10 );
3add_filter( 'image_send_to_editor', 'remove_width_and_height_attribute', 10 );
4function remove_width_and_height_attribute( $html ) {
5    return preg_replace( '/(height|width)="\d*"\s/', "", $html );
6}

レスポンシブで画像を%指定したときに便利です。

管理画面の投稿一覧にアイキチャッチを載せる

1//管理画面投稿一覧にアイキャッチサムネイル
2add_theme_support( 'post-thumbnails' );
3function manage_posts_columns($columns) {
4        $columns['thumbnail'] = __('Thumbnail');
5        return $columns;
6}
7function add_column($column_name, $post_id) {
8    //アイキャッチ取得
9    if ( 'thumbnail' == $column_name) {
10        $thum = get_the_post_thumbnail($post_id, array(50,50), 'thumbnail');
11    }
12    //使用していない場合「なし」を表示
13    if ( isset($stitle) && $stitle ) {
14        echo attribute_escape($stitle);
15    } else if ( isset($thum) && $thum ) {
16        echo $thum;
17    } else {
18        echo __('None');
19    }
20}
21add_filter( 'manage_posts_columns', 'manage_posts_columns' );
22add_action( 'manage_posts_custom_column', 'add_column', 10, 2 );

更新する時にわかりやすくて便利です

投稿から画像挿入した時に自動で作成される画像リンクを削除する

1add_filter( 'the_content', 'attachment_image_link_remove_filter' );
2function attachment_image_link_remove_filter( $content ) {
3    $content =  preg_replace(  array('{<a(.*?)(wp-att|wp-content/uploads)[^>]*><img}''{ wp-image-[0-9]*" /></a>}'), array('<img','" />'),  $content  );
4    return $content;
5}

これはwp-content/uploads配下の画像ファイル全てに適応されるので、アフィリエイト画像などを画像挿入で入れるとリンク切れになる場合があります

コメント入力欄

主な業務内容

  • ホームページ制作
  • ECサイト構築
  • SEO対策
  • システム構築
  • トレードシステム設計
  • 展示会の企画・設計
  • 日用雑貨の販売
PAGE TOP ↑