【 WordPress 】テンプレートをカスタマイズする ② – よく使う関数

WordPressWordPress

Contents

リストを取得

投稿のリストを取得する

get_posts

投稿データの配列を取得します

<?php $posts_array = get_posts( $args ); ?>

$args

  • 検索条件の array

初期値

<?php
$args = array(
	'posts_per_page'   => 5,
	'offset'           => 0,
	'category'         => '',
	'category_name'    => '',
	'orderby'          => 'date',
	'order'            => 'DESC',
	'include'          => '',
	'exclude'          => '',
	'meta_key'         => '',
	'meta_value'       => '',
	'post_type'        => 'post',
	'post_mime_type'   => '',
	'post_parent'      => '',
	'author'	   => '',
	'post_status'      => 'publish',
	'suppress_filters' => true 
);
?>

get_posts と同様に WP_Query でも投稿のループを生成することができます

# get_posts でのループ作成
<?php
$posts_array = get_posts($args);
if(!empty($posts_array)):
	foreach($posts_array as $post):
		setup_postdata($post);
?>
/* ループ内の処理*/
<?php
	endforeach;
elseif(empty($posts_array)):
?>
/* 投稿がない時の処理 */
<?php
endif; wp_reset_postdata();
?>
# WP_Query でのループ作成
<?php
$paged = get_query_var( 'paged',  1 )
$args = array(
	'post_type' => 'post',
	'posts_per_page' => 5,
	'paged' => $paged,
);
$posts_array = new WP_Query($array);
if($posts_array->have_posts()):
	while($posts_array->have_posts()):
		$posts_array->the_post();
?>
/* ループ内の処理 */
<?php
	endwhile;
else:
?>
/* 投稿がない場合の処理 */
<?php
endif; wp_reset_postdata();
?>

get_posts, WP_Query ともに tax_query パラメータを指定することで categorytag の条件を組み合わせてデータを取得することができます

#taxonomy_query の例
$args = array(
	'tax_query' => array(
		'relation' => AND,
		array(
			'taxonomy' => 'category',
			'terms' => array(1, 3, 5),
			'include_children' => false,
			'field' => 'term_id',
			'operator'=>'AND'
		),
		array(
			'taxnomy' => 'post_tag',
			'terms' => array( 'news', 'topics' ),
			'field' => 'slug',
			'include_children' => false,
			'operator' => 'NOT IN'
		)
	)
)
# (category の ID が 1 or 3 or 5) かつ (post_tag のスラッグが 'news' or 'topics' でない)もの

WP_Query は特定のキーワードにマッチする投稿を検索することができます

<?php $query = new WP_Query( array('s' => 'キーワード') ) ?>

カテゴリーの配列を取得する

get_categories

条件にマッチするカテゴリーのリストを取得します

<?php $categories = get_categories( $args );?>

$args

  • パラメータ
    • type
    • child_of
    • parent
    • orderby
    • order
    • hide_empty
    • hierarchical
    • exclude
    • include
    • number
    • taxonomy
    • pad_counts

初期値

<?php
$args = array(
	'type'                     => 'post',
	'child_of'                 => 0,
	'parent'                   => '',
	'orderby'                  => 'name',
	'order'                    => 'ASC',
	'hide_empty'               => 1,
	'hierarchical'             => 1,
	'exclude'                  => '',
	'include'                  => '',
	'number'                   => '',
	'taxonomy'                 => 'category',
	'pad_counts'               => false 
); 
?>

タグの配列を取得する

get_tags

条件を指定してタグのリストを取得します

<?php $tags_array = get_tags($args) ?>

$args

  • パラメータ
    • orderby
    • order
    • hide_empty
    • exclude
    • include
    • number
    • offset
    • fields
    • slug
    • search
    • name__like
    • description__like

初期値

<?php
$args = array(
	'orderby' => 'name',
	'order' => 'ASC',
	'hide_empty' => true,
	'exclude' => '',
	'include' => '',
	'number' => '',
	'offset' => '',
	'fields' => 'all',
	'slug' => '',
	'search' => '',
	'name__like' => '',
	'description__like' => ''
)
?>

タクソノミーの配列を取得する

get_taxonomies

登録済みタクソノミーのリストを取得します

<?php $taxonomies = get_taxonomies($args, $output, $operator) ?>

$args

  • 検索条件の 'key => value' の配列
    • name
    • object_type
    • label
    • singular_label
    • show_ui
    • show_tagcloud
    • publlic
    • update_count_callback
    • rewrite
    • query_var
    • manage_cap
    • edit_cap
    • delete_cap
    • assign_cap
    • _buildid

初期値
なし

$output

  • 出力形式
    • 'names'
    • 'objects'

初期値
'names'

$operator

$args に引数を複数入れたときの結合方法 (and または or)

初期値
and

ユーザーの配列を取得する

get_users

指定した条件をもとにユーザーのリストを取得する

<?php
$args = array(
	'blog_id'      => $GLOBALS['blog_id'],
	'role'         => '',
	'meta_key'     => '',
	'meta_value'   => '',
	'meta_compare' => '',
	'meta_query'   => array(),
	'date_query'   => array(),
	'include'      => array(),
	'exclude'      => array(),
	'orderby'      => 'login',
	'order'        => 'ASC',
	'offset'       => '',
	'search'       => '',
	'number'       => '',
	'count_total'  => false,
	'fields'       => 'all',
	'who'          => ''
);
$users = get_users( $args ); 
?>

$args

  • 検索条件のパラメータ

初期値
array()

詳細を取得

投稿の抜粋文を取得 / 表示する

the_excerpt

抜粋文をテキストで表示します
ループ内でのみ使用できます

<?php the_excerpt() ?>

get_the_excerpt

抜粋文を取得します
ループ内でのみ使用できます

<?php $excerpt = get_the_excerpt() ?>

投稿のサムネイル画像の表示 / 取得する

the_post_thumbnail

現在の投稿のサムネイル画像を表示します
ループ内でのみ使用できます

<?php the_post_thumbnail($size, $attr) ?>

$size

  • 画像サイズ (thumbnail, medium, large, full)
  • add_image_size() で定義したカスタムサイズのキーワード
  • array(幅(int), 高さ(int))

初期値
テーマの function.php 内で set_post_thumbnail_size() を使って設定したサイズ。

$attr

  • サムネイル画像を表示する HTML の img タグに含める属性/値の array

初期値
なし

# $attr のデフォルト
$default_attr = array(
	'src'   => $src,
	'class' => "attachment-$size",
	'alt'   => trim( strip_tags( $wp_postmeta->_wp_attachment_image_alt ) )
);

get_the_post_thumbnail

投稿のサムネイル画像を取得します

<?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>

$post_id

  • 投稿 ID

初期値
現在の投稿

$size

  • 画像サイズ (thumbnail, medium, large, full)
  • add_image_size() で定義したカスタムサイズのキーワード
  • array(幅(int), 高さ(int))

初期値
テーマの function.php 内で set_post_thumbnail_size() を使って設定したサイズ

$attr

  • サムネイル画像を表示する HTML の img タグに含める属性/値の array

初期値
なし

# $attr のデフォルト
$default_attr = array(
  'src'   => $src,	// アイキャッチ画像の URL
  'class' => "attachment-$size",	// 指定した大きさ
  'alt'   => trim( strip_tags( $attachment->post_excerpt ) ),	// アイキャッチ画像の抜粋
  'title' => trim( strip_tags( $attachment->post_title ) ),	// アイキャッチ画像のタイトル
);

特定の投稿を取得する

get_post

特定の投稿を取得します

<?php get_post( $id, $output, $filter ); ?>

$id

  • 取得したい投稿の ID

初期値
null (現在の投稿)

$output

  • 戻り値の型
    • 'OBJECT' - 投稿オブジェクト
      • ID (int): 投稿 ID
      • post_author (string): 投稿者 ID
      • post_name (string): 投稿のスラッグ
      • post_type (string): 投稿タイプ
      • post_title (string): 投稿のタイトル
      • post_date (string): 投稿日時
      • post_date_gmt (string): 投稿日時の GMT 表記
      • post_modified (string): 更新日時
      • post_modified_gmt (string): 更新日時の GMT 表記
      • post_content (string): 本文
      • post_excerpt (string): 抜粋
      • post_status (string): 公開ステータス
      • ping_status (string): ピンバック / トラックバックステータス
      • to_ping (string): ピン通知 URL
      • pinged (string): ピン通知済み URL
      • guid (string): 投稿へのリンクの書式になっている識別子
      • post_password (string): 閲覧パスワード
      • post_parent (int): 親 ID
      • comment_status (string): コメントステータス
      • comment_count (int): コメント数
      • menu_order (int): 固定ページの表示順序
      • post_mime_type (string): 添付ファイルのとき, MIME タイプ (image/png 等)
    • 'ARRAY_A' - 連想配列
    • 'ARRAY_N' - インデックス配列

初期値
'OBJECT'

$filter

  • 無害化のコンテキスト
    • 'raw'
    • 'edit'
    • 'db'
    • 'display'
    • 'attribute'
    • js

初期値
'raw'

投稿のデータを取得する

get_post_field

投稿の ID とフィールドを指定してデータを取得します

<?php get_post_field($field, $post_id, $context) ?>

$field (必須)

  • 投稿のフィールド名
    • get_post で取得できるフィールド('post_author', 'post_title' 等)を指定できます

初期値
なし

$post_id (必須)

  • 投稿 ID

初期値
なし

$context

  • 無害化(フィルター)の方法
    • 'raw'
    • 'edit'
    • 'db'
    • 'display'
    • 'attribute'
    • 'js'

投稿の ID を取得する

get_the_ID

現在の投稿の ID を取得します
ループ内でのみ使用できます

<?php $postid = get_the_ID() ?>

カテゴリーの詳細データを取得

get_category

カテゴリー ID or カテゴリーオブジェクトを指定して、カテゴリーの詳細データを取得します

<?php $cat = get_category($category, $output, $filter) ?>

$category (必須)

  • カテゴリーの ID
  • カテゴリー行オブジェクト

初期値
なし

$output

  • 'OBJECT'
  • 'ARRAY_A'
  • 'ARRAY_N'

初期値
'OBJECT'

$filter

  • フィルター名

初期値
'raw'

get_the_category

現在の投稿のカテゴリー詳細データを取得します
投稿 ID を指定することでループ外でも使用できます

<?php $cat = get_the_category($id) ?>

$id

  • 投稿 ID

初期値
現在の投稿の ID

タグの詳細データを取得する

get_tag

タグ ID またはタグオブジェクトを指定してタグの詳細データを取得します

<?php $tag_data = get_tag($tag) ?>

$tag

  • タグの ID
  • タグのオブジェクト

初期値
なし

$output

  • 'OBJECT'
  • 'ARRAY_A'
  • 'ARRAY_N'

初期値
'OBJECT'

$filter

  • フィルター名

初期値
'raw'

タクソノミー情報を取得する

get_taxonomy

タクソノミーの詳細情報を取得します

<?php $tax = get_taxonomy($taxonomy) ?>

$taxonomy

  • タクソノミー名

初期値
なし

投稿の作成者を取得する

get_the_author

投稿の作成者の表示名を取得します
ループ内でのみ使用できます

<?php $author = get_the_author() ?>

投稿のタイトルを取得する

get_the_title

投稿 ID をもとに投稿のタイトルを取得します

<?php echo get_the_title($id) ?>

$id

  • 投稿の ID
  • 投稿のオブジェクト

初期値
現在の投稿の ID (ループ内)

ユーザーのメタデータを取得する

get_user_meta

特定のユーザのメタデータを取得します

<?php $meta = get_user_meta($user_id, $key, $single) ?>

$user_id

  • ユーザー ID

初期値
なし

$key

  • 値を取得する meta_key (空文字の場合、全てのメタデータを取得します)

初期値
''

$single

  • true or false
    true ならメタデータの値、false なら配列を返す

初期値
false

投稿の日付を取得する

get_the_date

投稿の投稿日を取得します

<?php $pfx_date = get_the_date($format, $post_id) ?>

$format

  • 日付の書式
      • 'Y/m/d H:i:s l' => '2050/01/02 21:59:59 Sunday'
      • 'y-n-j g:i a D' => '50-1-2 9:59 pm Sun'
      • 'M, S, Y h:i A' => 'Jan, 2nd, 2050 09:59 PM'

初期値
オプションの設定値

サイトに関する情報を取得する

get_bloginfo

指定したサイト情報を取得します

<?php $bloginfo = get_bloginfo($show, $filter) ?>

$show

  • パラメータ
    • 'name'
    • 'description'
    • 'wpurl'
    • 'url'
    • 'admin_email'
    • 'charset'
    • 'version'
    • 'html_type'
    • 'text_direction'
    • 'language'
    • 'stylesheet_url'
    • 'stylesheet_directory'
    • 'template_url' / 'template_directory'
    • 'pingback_url'
    • 'atom_url'
    • 'rdf_url'
    • 'rss_url'
    • 'rss2_url'
    • 'comments_atom_url'
    • 'comments_rss2_url'

初期値
name

$filter

  • フィルター名

初期値
'raw'

リンク/パスを取得する

パーマリンクを取得 / 表示する

the_permalink

パーマリンクをテキストで表示します

<?php the_permalink( $post ); ?>

$post

  • 投稿または固定ページの ID

初期値
ループ内で使用した場合: 表示中の投稿の ID
アーカイブページでループ外で使用した場合: ループの最後の投稿の ID

get_permalink

パーマリンクを取得します

<?php $permalink = get_permalink( $id, $leavename ); ?>

$id

  • 投稿または固定ページの ID

初期値
ループ内で使用した場合: 表示中の投稿の ID
アーカイブページでループ外で使用した場合: ループの最後の投稿の ID

$leavename

  • true or false

true にした場合はパーマリンク構造を返します。
http://www.example.com/some-post-name ではなく http://www.example.com/%postname% を返します。)

初期値
false

カテゴリーアーカイブページのリンクを取得する

get_category_link

カテゴリー ID からカテゴリーのアーカイブページへのリンクを取得します

<?php $cat_link = get_category_link($category_id) ?>

$category_id

  • カテゴリー ID

初期値
なし

サイトの URL を取得

get_site_url

サイトの URL を取得します

<?php get_site_url($blog_id, $path, $scheme) ?>

$blog_id

  • ブログ ID

初期値
現在のブログ

$path
サイト URL に追加するパス

初期値
''

$scheme

  • スキーマ名 ('http', 'https', 'login', 'login_post', 'admin')

初期値
null (自動で判別)

home_url

サイトのホーム URL を取得します

<?php $url = home_url($path, $scheme) ?>

$path

  • ホーム URL に追加するパス

初期値
''

$schema

  • スキーマ名 ('http', 'https')

初期値
null (自動で判別)

アップロードディレクトリを取得する

wp_upload_dir

アップロードディレクトリを取得します

<?php $dir = wp_upload_dir($time, $create_dir, $refresh_cache) ?>

$time

  • 年月 ('yyyy/mm')

初期値
null

$create_dir

  • ディレクトリの作成を行う場合は true

初期値
true

$refresh_cache

  • キャッシュを更新するかどうか

初期値
false

その他

ループ内で次の投稿へ進める

the_post()

ループを次の投稿へ進めます

<使い方>

<?php
if ( have_posts() ) {
	while ( have_posts() ) {

		the_post(); ?>

		<h2><?php the_title(); ?></h2>

		<?php the_content(); ?>

	<?php }
}
?>

投稿がカテゴリーに属するか判別する

in_category

投稿が特定のカテゴリーに属するか判別します

<?php in_category($category, $_post) ?>

$category (必須)

  • カテゴリー ID
  • カテゴリー名
  • スラッグ

初期値
なし

$_post

  • 投稿 ID
  • 投稿オブジェクト

初期値
現在の投稿(ループ内)