10.

WordPress 主要独自関数完全ガイド (Loop / Enqueue / Hook / Conditional Tag)

編集
この記事の要点
  • ループ系: have_posts() / the_post() / get_the_title() / the_content()
  • クエリ: WP_Query / get_posts() / wp_query グローバル
  • アセット: wp_enqueue_script() / wp_enqueue_style()(直書きせず必ずこれを使う)
  • フック: add_action("init", fn) / add_filter("the_content", fn)
  • 条件分岐タグ: is_home() / is_single() / is_page() / is_user_logged_in()

1. ループ系関数

<?php
// メインクエリのループ (single.php / archive.php 等)
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title( '<h2>', '</h2>' );      // タイトル出力
        the_content();                      // 本文出力
        the_excerpt();                      // 抜粋
        the_permalink();                    // パーマリンク URL
        the_post_thumbnail( 'medium' );     // アイキャッチ
        the_author();                       // 著者
        the_date();                         // 投稿日
    endwhile;
endif;

// 値取得版 (get_ 接頭辞: echo せず return)
$title = get_the_title();
$content = get_the_content();
$url = get_permalink();
$thumb = get_the_post_thumbnail_url();

2. クエリ関数

<?php
// WP_Query (フル機能)
$query = new WP_Query([
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'category_name'  => 'news',
    'meta_query'     => [
        ['key' => 'featured', 'value' => '1'],
    ],
    'tax_query'      => [
        [
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'shoes',
        ],
    ],
    'orderby'        => 'date',
    'order'          => 'DESC',
]);

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        the_title();
    endwhile;
    wp_reset_postdata();   // ★ 必須: グローバル $post を元に戻す
endif;

// 軽量版: 単純な投稿配列を取得
$posts = get_posts([
    'numberposts' => 5,
    'category'    => 1,
]);
foreach ( $posts as $p ) {
    echo $p->post_title;
}

3. アセット読み込み (Enqueue)

functions.php や プラグインで CSS/JS を読み込む場合、必ず Enqueue 関数を使います。直接 <script src> を書くと依存解決や重複防止が効きません:

<?php
// functions.php
function my_theme_assets() {
    // CSS
    wp_enqueue_style(
        'my-style',                              // ハンドル名
        get_stylesheet_uri(),                    // URL
        [],                                      // 依存
        wp_get_theme()->get('Version')           // バージョン (キャッシュバスター)
    );

    // JS (フッターで読む)
    wp_enqueue_script(
        'my-script',
        get_template_directory_uri() . '/js/app.js',
        ['jquery'],                              // jQuery 依存
        '1.0.0',
        true                                     // in_footer
    );

    // JS に PHP 変数を渡す (localize)
    wp_localize_script('my-script', 'MY_APP', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('my_nonce'),
        'user_id'  => get_current_user_id(),
    ]);
}
add_action('wp_enqueue_scripts', 'my_theme_assets');

4. フック (Action / Filter)

種類意味
add_action()「タイミングで関数を実行」init, wp_head, save_post
add_filter()「値を加工して返す」the_content, excerpt_length
do_action()独自 Action を発火
apply_filters()独自 Filter を発火
remove_action() / remove_filter()登録解除
<?php
// Action: タイミングで実行
add_action('init', function() {
    // 初期化処理
});

add_action('save_post', function($post_id) {
    // 投稿保存後
}, 10, 1);

// Filter: 値を加工
add_filter('the_content', function($content) {
    return $content . '<p>記事の最後に追記</p>';
});

add_filter('excerpt_length', function($length) {
    return 50;  // 抜粋を 50 単語に
});

// 独自フックを定義
do_action('my_custom_event', $arg);
$value = apply_filters('my_custom_filter', $default_value);

5. テンプレート関数

<?php
// パーツ読み込み
get_header();                          // header.php
get_footer();                          // footer.php
get_sidebar();                         // sidebar.php
get_template_part('parts/card');       // parts/card.php
get_template_part('parts/card', 'featured');  // parts/card-featured.php

// 必須出力
wp_head();    // </head> 直前 (プラグイン CSS 等)
wp_footer();  // </body> 直前 (プラグイン JS 等)

// サイト情報
bloginfo('name');                      // サイト名
bloginfo('description');               // キャッチフレーズ
bloginfo('url');                       // サイト URL (PHP 5.6+ は site_url())
echo home_url();                       // ホーム URL
echo get_template_directory_uri();     // テーマ URL

// メニュー
wp_nav_menu([
    'theme_location' => 'primary',
    'container'      => 'nav',
    'menu_class'     => 'main-menu',
]);

6. 条件分岐タグ (Conditional Tags)

関数true になる条件
is_home()ブログのトップ
is_front_page()フロントページ (固定 or 最新投稿)
is_single()個別投稿
is_page()固定ページ
is_singular()個別投稿 OR 固定ページ
is_archive()アーカイブ (カテゴリ / タグ / 日付)
is_category() / is_tag()カテゴリ / タグアーカイブ
is_search()検索結果
is_404()404 ページ
is_user_logged_in()ログイン中
is_admin()管理画面
current_user_can('manage_options')権限チェック

7. ユーザー / メタ系

<?php
// 現在のユーザー
$user = wp_get_current_user();
$user_id = get_current_user_id();
echo $user->display_name;
echo $user->user_email;

// カスタムフィールド (post meta)
$value = get_post_meta($post_id, 'meta_key', true);  // 単一値
$values = get_post_meta($post_id, 'meta_key', false); // 配列
update_post_meta($post_id, 'meta_key', $new_value);
delete_post_meta($post_id, 'meta_key');

// ユーザーメタ
$nickname = get_user_meta($user_id, 'nickname', true);
update_user_meta($user_id, 'preferred_color', 'blue');

// オプション
$option = get_option('blogname');
update_option('my_setting', 'value');
delete_option('my_setting');

8. REST API / AJAX

<?php
// REST API エンドポイント追加
add_action('rest_api_init', function() {
    register_rest_route('myapp/v1', '/items', [
        'methods'  => 'GET',
        'callback' => function() {
            return ['items' => get_posts(['numberposts' => 10])];
        },
        'permission_callback' => '__return_true',
    ]);
});

// 管理画面 AJAX
add_action('wp_ajax_my_action', 'my_action_handler');         // ログイン済
add_action('wp_ajax_nopriv_my_action', 'my_action_handler');  // 未ログイン
function my_action_handler() {
    check_ajax_referer('my_nonce', 'nonce');   // CSRF 検証
    $data = sanitize_text_field($_POST['data']);
    wp_send_json_success(['result' => 'ok']);
}

9. セキュリティ系

  • サニタイズ: sanitize_text_field() / sanitize_email() / esc_url_raw() / wp_kses_post()
  • エスケープ: esc_html() / esc_attr() / esc_url() / esc_js()
  • Nonce: wp_create_nonce() / wp_verify_nonce() / check_admin_referer()
  • 権限: current_user_can() / user_can()
  • SQL: $wpdb->prepare() 必須、生 SQL は禁止

10. 公式リファレンスへのリンク

FAQ

Q: the_title()get_the_title() の違い
A: the_ 接頭辞は echo(直接出力)、get_the_ 接頭辞は return(値を返す)。変数に格納したいなら get_ 版。

Q: wp_reset_postdata() って?
A: WP_Query 後にグローバル $post を元に戻す関数。忘れるとループ後に表示が壊れる定番バグ。

Q: add_actionadd_filter、どっち使うか迷う
A: 値を受け取って加工して返すなら filter。何かを実行するだけなら action

編集
Post Share
子ページ
  1. do_action
  2. get_header
同階層のページ
  1. インストール方法(Ubuntu + Apache)
  2. Wordpressのインストール方法
  3. ローカル環境への導入方法
  4. PHPの使用方法
  5. DB設定
  6. DB接続方法
  7. index.phpをURLに含めないようにする方法
  8. コメントに絵文字を入力可能にする方法
  9. サイト(ドメイン)の引越し方法
  10. 独自の関数一覧
  11. エラー一覧
  12. Wordpressの一連の処理の流れ

最近更新/作成されたページ