タイトル: 独自の関数一覧
SEOタイトル: 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. ループ系関数
', '' ); // タイトル出力
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. クエリ関数
'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 関数を使います。直接 を書くと依存解決や重複防止が効きません:
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() | 登録解除 | — |
記事の最後に追記';
});
add_filter('excerpt_length', function($length) {
return 50; // 抜粋を 50 単語に
});
// 独自フックを定義
do_action('my_custom_event', $arg);
$value = apply_filters('my_custom_filter', $default_value);
5. テンプレート関数
直前 (プラグイン CSS 等)
wp_footer(); //