7
8

More than 3 years have passed since last update.

[自分用メモ]WordPressスニペット

Last updated at Posted at 2019-08-30

WordPress開発時に頻出のカスタマイズコードをメモとして記述していきます。
※随時更新

404ページ

404.php
<script>
mnt = 3;
url = "http://www.example.com/";
function jumpPage() {
location.href = url;
}
setTimeout("jumpPage()",mnt*1000)
</script>

//attachment_id=ページに404を返す
add_action( 'template_redirect', 'gs_attachment_template_redirect' );
function gs_attachment_template_redirect() {
    if ( is_attachment() ) { // 添付ファイルの個別ページなら
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
    }
}

固定ページやカテゴリーのID取得


//固定ページ
$page_data = get_page_by_path('parent_slug/child_slug');
$page_id = $page_data->ID;

$page_data = get_posts('name=sulg_name&post_type=page');
$page_id = $post_data[0]->ID;

//投稿
$post_data = get_page_by_path('slug_name', OBJECT, 'post');
$post_id = $post_data->ID;

$post_data = get_posts('name=sulg_name');
$post_id = $post_data[0]->ID;

// 固定フロントページ
$front_page_id = get_option( 'page_on_front' ); 

//カテゴリー
$cat_id = get_cat_ID( $cat_name );
$cat_obj = get_category_by_slug( $slug );
$cat_id = $cat_obj->term_id;  //$cat_obj->cat_IDでもOK

Advanced Custom Fieldsのループ出力

acf-loop.php

<?php if(have_rows('親')): ?>
<?php while(have_rows('親')): the_row(); ?>
<?php the_sub_field('sub_field_name1'); ?>
<?php if(have_rows('子')): ?>
<?php while(have_rows('子')): the_row(); ?>
<?php the_sub_field('sub_field_name2'); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

本文の文字数制限

echo wp_trim_words( get_the_content(), 55, '...' );

カテゴリー情報取得

$cat = get_the_category();
$cat = $cat[0];
echo $cat->category_nicename;
echo $cat->cat_name;
echo $cat->category_parent; //親カテゴリーのID

アイキャッチ画像サイズ

add_action( 'after_setup_theme', 'baw_theme_setup' );
function baw_theme_setup() {
 add_image_size('small_thumbnail', 90, 90 ,true );
 add_image_size('page_eyecatch-image', 615, 115, true );
 add_image_size( '150_thumbnail', 150, 75, true );
 add_image_size('280_thumbnail', 280, 125, true );
}

〇日以内の投稿にNEWマークをつける

$post_time = get_the_time('U');
$days = 7; //New!を表示させる日数
$last = time() - ($days * 24 * 60 * 60);
if ($post_time > $last) {
echo '<span class="new-txt">NEW!</span>';
}

All in One SEO Pack をアーカイブページでも有効化


add_filter( 'aioseop_description', 'custom_aioseop_description' );
function custom_aioseop_description( $description ) {
  if ( is_category() ) {
    $description = 'category archive description here ...';
  } else if ( is_date() ) {
    $description = 'date archive description here ...';
  } else if ( is_archive() ) {
    $description = 'other archive description here ...';
  }
  return $description;
}

画像パスの短縮


function imagepassshort($arg) {
  $content = str_replace(array('"../../','"../','"./'), '"' . get_template_directory_uri() . '/', $arg);
  return $content;
}
add_action('the_content', 'imagepassshort');

固定ページの親ページを判定


//親ページのslugで判定
function is_parent_slug()
{
    global $post;
    if ($post->post_parent) {
        $post_data = get_post($post->post_parent);
        return $post_data->post_name;
    }
}
//親ページのIDで判定
function is_parent_id()
{
    global $post;
    if ($post->post_parent) {
        $post_data = get_post($post->post_parent);
        return $post_data->ID;
    }
}

パーマリンクから'/category'を消す

functions.php
//パーマリンクカテゴリ削除
add_filter('user_trailingslashit', 'remcat_function');
function remcat_function($link) {
    return str_replace("/category/", "/", $link);
}
add_action('init', 'remcat_flush_rules');
function remcat_flush_rules() {
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}
add_filter('generate_rewrite_rules', 'remcat_rewrite');
function remcat_rewrite($wp_rewrite) {
    $new_rules = array('(.+)/page/(.+)/?' => 'index.php?category_name='.$wp_rewrite->preg_index(1).'&paged='.$wp_rewrite->preg_index(2));
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

cronイベントフック


//cronにイベントを登録してくれると同時にフックも作成できる。
//さらにそのイベントは、誰かがサイトに訪問したときに予定した時刻を過ぎていれば実行される。
wp_schedule_single_event( $timestamp, $hook, $args );

//使用例
function change_post_status_schedule( $pid ) { // 投稿を保存したら公開日の◯◯後にステータスを変更
    if ( get_post_type() == 'post' ) : // 投稿タイプ指定
        /*
         * 何日後に処理したいかを指定する
         * 1年 : ' +1 year JST'
         * 1ヶ月 : ' +1 month JST'
         * 1週間 : ' +1 week JST'
         * 1日 : ' +1 day JST'
         **/
        $time_stamp = strtotime( get_the_modified_date('YmdHi', $pid) . ' +1 year JST' );
        wp_schedule_single_event( $time_stamp, 'change_post_status_torigger', array($pid) );
    endif ;
}
add_action('save_post','change_post_status_schedule');

// スケジュールされる動作を記述
function change_post_status( $pid ) { // 投稿ステータスをゴミ箱に変更
    /*
     * 変更ステータス例
     * ゴミ箱 : 'trash'
     * 非公開 : 'private'
     * 下書き : 'draft'
     **/
    wp_update_post( array( 'ID' => $pid, 'post_status' => 'trash' ) );
}
add_action('change_post_status_torigger', 'change_post_status');

ページネーション


/**
* ページネーション出力関数
* $paged : 現在のページ
* $pages : 全ページ数
* $range : 左右に何ページ表示するか
* $show_only : 1ページしかない時に表示するかどうか
*/
function pagination( $pages, $paged, $range = 2, $show_only = false ) {

    $pages = ( int ) $pages;    //float型で渡ってくるので明示的に int型 へ
    $paged = $paged ?: 1;       //get_query_var('paged')をそのまま投げても大丈夫なように

    //表示テキスト
    $text_first   = "« 最初へ";
    $text_before  = "<<";
    $text_next    = ">>";
    $text_last    = "最後へ »";

    if ( $show_only && $pages === 1 ) {
        // 1ページのみで表示設定が true の時
        echo '<div class="pager"><span class="current pager">1</span></div>';
        return;
    }

    if ( $pages === 1 ) return;    // 1ページのみで表示設定もない場合

    if ( 1 !== $pages ) {
        //2ページ以上の時
        echo '<div class="pager"><ul>';
        if ( $paged > $range + 1 ) {
            // 「最初へ」 の表示
            echo '<li><a href="', get_pagenum_link(1) ,'" class="first">', $text_first ,'</a></li>';
        }
        if ( $paged > 1 ) {
            // 「前へ」 の表示
            echo '<li><a href="', get_pagenum_link( $paged - 1 ) ,'" class="prev">', $text_before ,'</a></li>';
        }
        for ( $i = 1; $i <= $pages; $i++ ) {

            if ( $i <= $paged + $range && $i >= $paged - $range ) {
                // $paged +- $range 以内であればページ番号を出力
                if ( $paged === $i ) {
                    echo '<li><em class="current pager">', $i ,'</em></li>';
                } else {
                    echo '<li><a href="', get_pagenum_link( $i ) ,'" class="pager">', $i ,'</a></li>';
                }
            }

        }
        if ( $paged < $pages ) {
            // 「次へ」 の表示
            echo '<li><a href="', get_pagenum_link( $paged + 1 ) ,'" class="next">', $text_next ,'</a></li>';
        }
        if ( $paged + $range < $pages ) {
            // 「最後へ」 の表示
            echo '<li><a href="', get_pagenum_link( $pages ) ,'" class="last">', $text_last ,'</a></li>';
        }
        echo '</ul></div>';
    }
}

タイトルタグ出力


/**
 * titleタグの出力(ページ階層も反映)
 */
function setup_my_theme() {
  add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'setup_my_theme');
function change_title_tag( $title ) {
  if(is_front_page()) {
    return;
  } elseif ( is_page() ) {
    $title = get_the_title($post->ID);
    $title .= ' | ';
    foreach ( get_post_ancestors($post->ID) as $parid ) {
      $title .= get_page($parid)->post_title;
      $title .= ' | ';
    }
    $title .= get_bloginfo();
  }
  return $title;
}
add_filter( 'pre_get_document_title', 'change_title_tag' );
function change_title_separator( $sep ){
  $sep = ' | ';
  return $sep;
}
add_filter( 'document_title_separator', 'change_title_separator' );

自動整形を無効化


/**
 * 固定ページでは自動整形を停止
 */
add_filter('the_content', 'wpautop_filter', 9);
function wpautop_filter($content) {
  global $post;
  $remove_filter = false;
  $arr_types = array('page'); //適用させる投稿タイプを指定
  $post_type = get_post_type( $post->ID );
  if (in_array($post_type, $arr_types)) $remove_filter = true;
  if ( $remove_filter ) {
    remove_filter('the_content', 'wpautop');
    remove_filter('the_excerpt', 'wpautop');
  }
  return $content;
}

ウィジェット有効化


/**
 * ウィジェット追加
 */
function custom_widgets_init() {
    register_sidebar( array(
        'name'        => 'トップページ',
        'id'            => 'my-custom-sidebar',
        'description'   => 'トップページに表示',
        'before_widget' => '<div class="move widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<p class="widget-title">',
        'after_title'   => '</p>',
    ));
}
add_action( 'widgets_init', 'custom_widgets_init' );

// テーマに出力
if( is_active_sidebar( 'my-custom-sidebar' ) ){
    dynamic_sidebar('my-custom-sidebar');
}

固定ページの親を判定


/**
 * 固定ページの親ページを判定
 */
function is_parent_slug()
{
    global $post;
    if ($post->post_parent) {
        $post_data = get_post($post->post_parent);
        return $post_data->post_name;
    }
}

//使用例
if (is_parent_slug() === '親ページのスラッグ') {
   //子ページに対する処理
}

カスタムメニューを有効化


/**
 * カスタムメニュー
 */
function add_theme_support_cb()
{
    register_nav_menus(array(
      'main-menu' => 'メインメニュー',
      'sub-menu' => 'サブメニュー'
    ));
}
add_action('after_setup_theme', 'add_theme_support_cb');

//テーマに出力
wp_nav_menu(array(
  'theme_location' => 'main-menu',
  'container' => false,
  'menu_class' => '',
  'menu_id' => '',
  'walker' => new themeslug_walker_nav_menu,
  'link_before' => '<span>',
  'link_after' => '</span>'
));

head内の不要な要素を削除

/**
 * ヘッダー内で読み込まれる不要なライブラリを削除
 */
function add_files()
{
    wp_deregister_script('jquery');
    wp_deregister_script('jquery-migrate');
    wp_enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', "", null, false);
    wp_enqueue_script('jquery-migrate', '//code.jquery.com/jquery-migrate-1.4.1.min.js', array( 'jquery' ), null, false);
    wp_dequeue_style('wp-block-library');
}
add_action('wp_enqueue_scripts', 'add_files');


/**
 * ヘッダー内でデフォルトで読み込まれている不要なコードを削除
 */
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');

管理画面の「投稿」ラベルを変更


/*
 * デフォルト「投稿」→「ブログ」。
 */

function change_post_menu_label() {

    global $menu;
    global $submenu;
    $menu[5][0] = 'ブログ';
    $submenu['edit.php'][5][0] = 'ブログ一覧';
    $submenu['edit.php'][10][0] = '新しいブログ';
    $submenu['edit.php'][16][0] = 'タグ';

}

function change_post_object_label() {

    global $wp_post_types;
    $labels = &$wp_post_types['post']->labels;
    $labels->name = 'ブログ';
    $labels->singular_name = 'ブログ';
    $labels->add_new = _x('追加', 'ブログ');
    $labels->add_new_item = 'ブログの新規追加';
    $labels->edit_item = 'ブログの編集';
    $labels->new_item = '新規ブログ';
    $labels->view_item = 'ブログを表示';
    $labels->search_items = 'ブログを検索';
    $labels->not_found = '記事が見つかりませんでした';
    $labels->not_found_in_trash = 'ゴミ箱に記事は見つかりませんでした';

}

add_action( 'init', 'change_post_object_label' );
add_action( 'admin_menu', 'change_post_menu_label' );

任意のURLでアーカイブを作成



/* 投稿アーカイブページの作成 */
function post_has_archive( $args, $post_type ) {

    if ( 'post' == $post_type ) {
        $args['rewrite'] = true;
        $args['has_archive'] = 'blogs'; //任意のスラッグ名
    }
    return $args;

}
add_filter( 'register_post_type_args', 'post_has_archive', 10, 2 );

カスタマイザー


/* テーマカスタマイザー
---------------------------------------------------------- */
add_action( 'customize_register', 'theme_customize' );

function theme_customize($wp_customize){

  //ロゴ画像
  $wp_customize->add_section( 'logo_section', array(
    'title' => 'ロゴ画像', //セクションのタイトル
    'priority' => 59, //セクションの位置
    'description' => 'ロゴ画像を使用する場合はアップロードしてください。画像を使用しない場合はタイトルがテキストで表示されます。', //セクションの説明
  ));

  $wp_customize->add_setting( 'logo_url' );
  $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'logo_url', array(
    'label' => 'ロゴ画像',//セッティングのタイトル
    'section' => 'logo_section', //セクションID
    'settings' => 'logo_url', //セッティングID
    'description' => 'ロゴ画像を設定してください。', //セッティングの説明
  )));

}

/* テーマカスタマイザーで設定された画像のURLを取得
---------------------------------------------------------- */
//ロゴ画像
function get_the_logo_url(){
    return esc_url( get_theme_mod( 'logo_url' ) );
}

テーマに出力


<?php
$logo_url = get_the_logo_url('logo_url'); //変数logo_urlを宣言
if($logo_url): //変数logo_urlに値が入っていれば
?> 

    <div class="logo"><a href="<?php echo home_url( '/' ); ?>"><img src="<?php echo get_the_logo_url(); ?>" alt="<?php bloginfo('name'); ?>" /></a></div>

<?php else: ?>//変数logo_urlの値が空なら

    <div class="title"><a href="<?php echo home_url( '/' ); ?>"><?php bloginfo('name'); ?></a></div>

<?php endif; ?>

年別アーカイブ


function my_archives( $content ){
  $content['type']  = 'yearly';
  $content['before']    = '';
    $content['after']   = '';
    $content['limit']   = 5; //n年分を表示
    return $content;
}
add_filter( 'widget_archives_args','my_archives');

年別アーカイブリストの出力結果を調整


function filter_to_archives_link( $link_html, $url, $text, $format, $before, $after ) {
  $text .= "年";
  $my_year = '/' . get_query_var('year') ;

  if (strstr($link_html, $my_year)) {
    $current_class = 'current';
  }

  if ( 'html' === $format ) {

    $link_html = "<li class='menu-list__item $current_class'>$before<a href='$url'>$text</a></li>\n";

  }
  return $link_html;
}
add_filter( 'get_archives_link', 'filter_to_archives_link', 10, 6 );

the_archive_titleから余計な文字を削除


add_filter( 'get_the_archive_title', function ($title) {
  if (is_category()) {
      $title = single_cat_title('',false);
  } elseif (is_tag()) {
      $title = single_tag_title('',false);
    } elseif (is_tax()) {
        $title = single_term_title('',false);
    } elseif (is_post_type_archive() ){
        $title = post_type_archive_title('',false);
    } elseif (is_date()) {
        $title = get_the_time('Y年');
    } elseif (is_search()) {
        $title = '検索結果:'.esc_html( get_search_query(false) );
    } elseif (is_404()) {
        $title = '「404」ページが見つかりません';
    } else {

    }
    return $title;
});
7
8
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
7
8