【WordPress】functions.phpによく書くことまとめ

WordPressでサイトを作る上でとても重要なサポートをしてくれるfunctions.php。

色んなサイトを作る中でよく記述することになるものを、備忘録としてここに書いておきます。

スポンサーリンク

 

※functions.phpでエラーが出ると管理画面(ダッシュボード)にアクセスできくなる事もありますので、作業をする前にバックアップを取ること、慎重に作業を行うことが大事です。

 

functions.phpでよくあるエラーはコピペなどで「<?php」「?>」の開始、終了タグが重複してしまうこと。

そうならないように、予め「最初」と「最後」にそれぞれ記述し、中には絶対重複しないよう注意する。

 

 

アイキャッチ画像選択の表示

add_theme_support('post-thumbnails');

 

ウィジェットの設置

register_sidebar();

 

「・・・」を「続きを読む」に変換

function new_excerpt_more( $more ) {
return ' <a href="'. get_permalink( get_the_ID() ) . '"> …続きを読む</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );

 

記事本文の文字数制限

function my_excerpt( $length ) {
global $post;
$content = mb_substr( strip_tags( $post -> post_content ), 0, $length );
$content = $content . ' ... <a class="more" href="'. get_permalink() . '">[read more]</a>';
return $content;
}

 

大元のjQueryの読み込み

function load_script(){
    wp_enqueue_script('jquery');
}
add_action('init', 'load_script');

 

検索条件が未入力時にsearch.phpにリダイレクトする

function set_redirect_template(){
	if (isset($_GET['s']) && empty($_GET['s'])) {
		include(TEMPLATEPATH . '/search.php');
		exit;
	}
}
add_action('template_redirect', 'set_redirect_template');

 

titleタグをページ毎に設定する

function func_title(){
	if (is_single())
	{
		//投稿ページのとき、投稿タイトル+カテゴリー名
		$cat = get_the_category();
		$cat = $cat[0];
		$cat_name = $cat->name;
		$title = get_the_title().'-'.$cat_name;
	}
	elseif (is_page())
	{
		//固定ページのとき、ページタイトル+サイトタイトル
		$title = get_the_title().'-'.get_option('blogname');
	}
	elseif (is_category())
	{
		//カテゴリーページのとき、カテゴリー名+サイトタイトル
		$cat = get_the_category();
		$cat = $cat[0];
		$cat_name = $cat->name;
		$title = $cat_name.'-'.get_option('blogname');
	}
	elseif (is_404())
	{
		//ページがみつからないとき
		$title = 'お探しのページが見つかりませんでした';
	}
	else
	{
		//トップページのとき、その他のとき、サイトタイトルを表示
		$title = get_option('blogname');
	}
	return $title;
}
add_action('init','func_title');

 

固定ページ、カテゴリーごと表示

function Include_my_php($params = array()) {
    extract(shortcode_atts(array(
        'file' => 'default'
    ), $params));
    ob_start();
    include(get_theme_root() . '/' . get_template() . "/$file.php");
    return ob_get_clean();
}
 
add_shortcode('myphp', 'Include_my_php');

 

moreタグのjump位置を無効

function themename_modify_readmore()
{
    return '<a href="' . get_permalink() . '" class="more-link">続きを読む</a>';
}
add_filter('the_content_more_link', 'themename_modify_readmore');

 

JPEG画像リサイズ時の圧縮率

add_filter('jpeg_quality', function($arg){return 90;});

 

「ブログ名>>記事タイトル – カテゴリ名」表示(SEO対策)

function my_title($title) {
    if(is_single()){        
        $temp = '';
        $category = get_the_category();
        foreach($category as $val){
            $temp .= ' - '.$val->name;
        }
        $title = $title . $temp;
        return $title;
    } else {    
        return $title;
    }
}
add_filter('wp_title', 'my_title');

 

パンくずリスト

function breadcrumb(){
    global $post;
    $str ='';
    if(!is_home()&&!is_admin()){
        $str.= '<div id="breadcrumb" class="cf"><div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">';
        $str.= '<a href="'. home_url() .'" itemprop="url"><span itemprop="title">ホーム</span></a> &gt;</div>';
 
        if(is_category()) {
            $cat = get_queried_object();
            if($cat -> parent != 0){
                $ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
                foreach($ancestors as $ancestor){
                    $str.='<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a href="'. get_category_link($ancestor) .'" itemprop="url"><span itemprop="title">'. get_cat_name($ancestor) .'</span></a> &gt;</div>';
                }
            }
        $str.='<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a href="'. get_category_link($cat -> term_id). '" itemprop="url"><span itemprop="title">'. $cat-> cat_name . '</span></a></div>';
        } elseif(is_page()){
            if($post -> post_parent != 0 ){
                $ancestors = array_reverse(get_post_ancestors( $post->ID ));
                foreach($ancestors as $ancestor){
                    $str.='<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a href="'. get_permalink($ancestor).'" itemprop="url"><span itemprop="title">'. get_the_title($ancestor) .'</span></a></div>';
                }
            }
        } elseif(is_single()){
            $categories = get_the_category($post->ID);
            $cat = $categories[0];
            if($cat -> parent != 0){
                $ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
                foreach($ancestors as $ancestor){
                    $str.='<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a href="'. get_category_link($ancestor).'" itemprop="url"><span itemprop="title">'. get_cat_name($ancestor). '</span></a> &gt;</div>';
                }
            }
            $str.='<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a href="'. get_category_link($cat -> term_id). '" itemprop="url"><span itemprop="title">'. $cat-> cat_name . '</span></a></div>';
        } else{
            $str.='<div>'. wp_title('', false) .'</div>';
        }
        $str.='</div>';
    }
    echo $str;
}

 

カスタム投稿タイプ作成

function create_post_type() {
  $exampleSupports = [
    'title',
    'editor',
    'thumbnail',
    'revisions'
  ];

  // add post type
  register_post_type( 'sample',
    array(
      'label' => 'ラベル表示名',
      'public' => true,
      'has_archive' => true,
      'menu_position' => 5,
      'supports' => $exampleSupports
    )
  );

  // add taxonomy
  register_taxonomy(
    'sample_taxonomy',
    'sample',
    array(
      'label' => '◯◯タグ',
      'labels' => array(
        'all_items' => '◯◯タグ一覧',
        'add_new_item' => '新規◯◯タグを追加'
      ),
      'hierarchical' => true
    )
  );
}

add_action( 'init', 'create_post_type' );

 


最後までお読みいただき、ありがとうございます。

投稿日: 2017-06-17
カテゴリー: WEB | 投稿者: NOR
 

全コンテンツ新着記事

  • iPhone Xに機種変更して気付いたiTunesの落とし穴
  • 2017年11月3日発売だったiPhoneX(アイフォーン10)。

    予約開始が同年10月27日16:01からだったので、私は15:59から携帯を握りしめ、16:00:45から予約ページの更新を繰り返しながら、ページが表示されるとすぐ予約の申込みを完了しました。

    その成果あってか、発売日の11月3日の午前中には受け取りにいくことができました。

     

    続きを読む