WordPress のテーマを直すときに、よく使うコードをまとめました。ループ・メニュー・カスタム投稿・サイドバー・カスタムフィールド・ショートコード・ウィジェットの 7 つです。テンプレートのファイルに書くものと、functions.php に書くものがあるので、それぞれに貼る場所を書いています。
functions.php に足すときは、テーマを更新しても消えないように、子テーマの functions.php に書くのがおすすめです。同じ名前の関数がほかにあると画面が真っ白になるので、関数名には自分のサイトの頭の文字を付けておくと安全です。
投稿の一覧を出す:ループ
テンプレートのファイル(index.php・archive.php など)で、投稿を順に出す基本の形です。投稿がないときの文も出します。
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
<div class="entry-content">
<?php the_content(); ?>
</div>
</article>
<?php endwhile; ?>
<?php else : ?>
<p>投稿が見つかりませんでした。</p>
<?php endif; ?>
タイトルと抜粋だけを出す、いちばん短い形です。一覧のページで本文の代わりに抜粋を出したいときに使います。
if (have_posts()) :
while (have_posts()) : the_post();
the_title();
the_excerpt();
endwhile;
endif;
functions.php に書くと、管理画面の「外観」→「メニュー」で「Header Menu」の場所を選べるようになります。テンプレートでは wp_nav_menu( array( 'theme_location' => 'header-menu' ) ) で出します。
function register_my_menu()
{
register_nav_menu('header-menu', __('Header Menu'));
}
add_action('init', 'register_my_menu');
投稿タイプを足す:register_post_type
「お知らせ」「実績」など、ふつうの投稿と分けたいときに使います。functions.php に書きます。show_in_rest を true にしないと、ブロックエディタで編集できません。
function create_custom_post_type() {
register_post_type(
'custom_post',
array(
'labels' => array(
'name' => __('カスタム投稿'), // 管理画面の表記
'singular_name' => __('カスタム投稿')
),
'public' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'thumbnail'),
'menu_icon' => 'dashicons-admin-post', // アイコン設定
'show_in_rest' => true, // ブロックエディタ対応(重要!)
'rewrite' => array('slug' => 'custom-slug'), // URLのスラッグ指定
)
);
}
add_action('init', 'create_custom_post_type');
いちばん短い形です。名前と、一覧のページを持つかだけを決めています。
function create_post_type()
{
register_post_type(
'movie',
array(
'labels' => array(
'name' => __('Movies'),
'singular_name' => __('Movie')
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_post_type');
アイキャッチなどを使えるようにした形です。上の例と同じファイルに貼るときは、関数名と投稿タイプの名前がぶつからないようにします。
// 上の「カスタム投稿」の例と一緒に貼るときは、関数名がぶつからないように名前を変える
function create_custom_type_post_type()
{
register_post_type(
'custom_type',
array(
'labels' => array(
'name' => __('Custom Types'),
'singular_name' => __('Custom Type')
),
'public' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'thumbnail'),
)
);
}
add_action('init', 'create_custom_type_post_type');
投稿タイプを足したあとは、管理画面の「設定」→「パーマリンク」を開いて「変更を保存」を押してください。押さないと、その投稿の URL が 404 になることがあります。
functions.php に書くと、「外観」→「ウィジェット」に新しいエリアが出ます。テンプレートでは dynamic_sidebar( 'custom-sidebar' ) で出します。
function my_custom_sidebar() {
register_sidebar(array(
'name' => __('My Custom Sidebar', 'text-domain'),
'id' => 'custom-sidebar',
'description' => __('サイドバーの右側に表示されるウィジェットエリアです。'),
'before_widget' => '<section id="%1$s" class="widget %2$s">', // 各ウィジェットを囲むタグ
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">', // タイトルを囲むタグ
'after_title' => '</h2>',
));
}
add_action('widgets_init', 'my_custom_sidebar');
投稿に入力欄を足す:add_meta_box
投稿の編集画面に、自分の入力欄(カスタムフィールド)を足すコードです。保存のときに、nonce・自動保存・権限の 3 つを確かめてから保存しています。この 3 つを省くと、ほかの人に値を書きかえられるおそれがあるので、まねするときも残してください。
// 1. メタボックスの追加
function add_custom_meta_box() {
add_meta_box(
'custom_meta_box',
__('カスタムフィールド', 'textdomain'),
'custom_meta_box_callback',
'post' // 投稿タイプ
);
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// 2. 入力フォームの表示
function custom_meta_box_callback($post) {
// セキュリティ用:Nonce(トークン)の発行
wp_nonce_field('custom_save_meta_box_data', 'custom_meta_box_nonce');
// 現在保存されている値を取得
$value = get_post_meta($post->ID, '_my_custom_key', true);
echo '<label for="my_custom_field">' . __('入力内容:', 'textdomain') . '</label>';
echo '<input type="text" id="my_custom_field" name="my_custom_field" value="' . esc_attr($value) . '" style="width:100%;">';
}
// 3. データの保存処理
function save_custom_meta_box_data($post_id) {
// セキュリティチェック:Nonceの確認
if (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], 'custom_save_meta_box_data')) {
return;
}
// 自動保存時はスキップ
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
// 権限チェック
if (!current_user_can('edit_post', $post_id)) return;
// 値の保存
if (isset($_POST['my_custom_field'])) {
update_post_meta($post_id, '_my_custom_key', sanitize_text_field($_POST['my_custom_field']));
}
}
add_action('save_post', 'save_custom_meta_box_data');
ショートコードを作る:add_shortcode
functions.php に書くと、記事の中で [custom] と書いた所に「Hello, World!」が出ます。ショートコードの関数は、echo ではなく return で返すのが決まりです。
function custom_shortcode()
{
return 'Hello, World!';
}
add_shortcode('custom', 'custom_shortcode');
ウィジェットを作る:WP_Widget
「外観」→「ウィジェット」で置ける、自分のウィジェットを作るコードです。表示(widget)・管理画面の入力欄(form)・保存(update)の 3 つをそろえ、最後に register_widget で登録します。出す文字は esc_html でエスケープしています。
class Custom_Widget extends WP_Widget
{
function __construct()
{
parent::__construct('custom_widget', __('カスタムウィジェット', 'text_domain'));
}
// ウィジェットの表示処理
public function widget($args, $instance)
{
$title = apply_filters('widget_title', $instance['title'] ?? '');
echo $args['before_widget'];
if ($title) echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
echo '<p>' . esc_html__( 'こんにちは!' ) . '</p>';
echo $args['after_widget'];
}
// 管理画面のフォーム設定
public function form($instance)
{
$title = $instance['title'] ?? '';
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('タイトル:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>">
</p>
<?php
}
// フォーム内容の保存処理
public function update($new_instance, $old_instance)
{
$instance = [];
$instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
return $instance;
}
}
// ウィジェットを登録する(これがないと、ウィジェットの一覧に出てこない)
add_action( 'widgets_init', function () {
register_widget( 'Custom_Widget' );
} );
まとめ
- ループはテンプレートのファイル、メニュー・投稿タイプ・サイドバー・入力欄・ショートコード・ウィジェットは functions.php に書く
- functions.php は子テーマに書き、関数名には頭の文字を付ける
- 投稿タイプを足したら、パーマリンクの設定を一度保存する
- 入力欄の保存は、nonce・自動保存・権限を確かめてから


