【WordPress】用語集を自作する方法

2019年1月29日
用語集

WordPressで「用語集」を設置する際に、プラグインを使いたくなかったため自作した。

前提

下記のクラスを定義済みの想定とする。

手順

用語集を表示するクラスを定義する

下記のクラスをPHPで定義する。

final class Terminology extends StaticClass {
    const INITIAL_KEY = 'initial';

    public static function show() {
        $datas              = self::get_post_datas();
        $current_initial    = null;

        while ( $datas->have_posts() ) {
            $datas->the_post();

            $current_id     = get_the_ID();
            $next_initial   = get_post_meta( $current_id, self::INITIAL_KEY, true );

            if ( $current_initial !== $next_initial ) {
                $current_initial === null ? 
                    printf( '<h2>%s</h2><ul>', $next_initial ) : 
                    printf( '</ul><h2>%s</h2><ul>', $next_initial )
                ;

                $current_initial = $next_initial;
            }

            $permalink  = get_the_permalink();
            $title      = get_the_title();

            echo <<< "EOT"
<li>
    <a href="$permalink">$title</a>
</li>
EOT;
        }

        if ( $current_initial !== null ) echo '</ul>';
    }

    private static function get_post_datas() {
        $conditions = [
            'meta_key'              => self::INITIAL_KEY,
            'orderby'               => 'meta_value',
            'order'                 => 'ASC',
            'ignore_sticky_posts'   => 1,
            'posts_per_page'        => -1,
        ];

        return new WP_Query( $conditions );
    }
}

編集画面に頭文字を入力する領域を追加する

admin_menuアクションフックとsave_postアクションフックを用いて、編集画面に用語の頭文字を入力する領域を追加する。

function add_initial_field() {
    $on_show = function() {
        global $post;

        $key    = Terminology::INITIAL_KEY;
        $id     = get_post_meta( $post->ID, $key, true );
    
        echo <<< EOT
    <input type="text" name="{$key}" value="{$id}" size="50">
EOT;
    };

    add_meta_box( 
        Terminology::INITIAL_KEY, 
        '頭文字', 
        $on_show, 
        'post', 
        'normal'
    );
}

function save_initial( $post_id ) {
    $key = Terminology::INITIAL_KEY;

    empty( $_POST[ $key ] ) ?
        delete_post_meta( $post_id, $key ) :
        update_post_meta( $post_id, $key, $_POST[ $key ] )
    ;
}

add_action( 'admin_menu', 'add_initial_field' );
add_action( 'save_post', 'save_initial' );

表示させたい箇所で関数を呼ぶ

テンプレートファイルの表示させたい箇所で下記の関数を呼ぶ。

Terminology::show();

編集画面で頭文字を入力する

先ほど編集画面に追加した領域に対し、頭文字を入力する。( ※ 文字はひらがなかつ濁点なしを想定 )

頭文字

これでその記事が用語集に追加される。

<h2>あ</h2>
<ul>
	<li>
   		<a href="http://sample.com/aaa/">あああ</a>
	</li>
	<li>
    	<a href="http://sample.com/aiu/">あいう</a>
	</li>
</ul>
<h2>い</h2>
<ul>
	<li>
		<a href="http://sample.com/iii/">いいい</a>
	</li>
</ul>