自分で取得する記事をいじったりする上級者向けです。
疑問
WordPressで投稿記事を取得する時のパラメータを変えて、独自の一覧を表示させたい!
特定記事を取得して表示したい場合などに使えます。
投稿記事の取得パラメータを変えてる一覧を取得する方法
できるだけ修正を減らす場合は「WP_Query()」を使ってサブクエリにします。
WP_Query()に渡すパラメータ「$args」で検索条件を変えることができます。
パラメータ情報は本家サイトを見た方が早いし分かりやすいです。
サブクエリの処理フロー
サブクエリの処理フローは、下記のようになっています。
- $argsを設定
- WP_Query($args)を実行
- 記事を成形
$argsを設定
独自の記事一覧を取得するためのパラメータ設定をします。
WP_Query($args)を実行
指定したパラメータをWP_Queryに渡して実行すると、データを取得できます。
記事を成形
have_posts()を使って、記事があれば記事を成形して一覧を作成します。
指定した投稿IDを取得するショートコード
サブクエリを使って、指定した投稿ID(カンマ区切りにすれば複数可能)を取得するショートコードを紹介します。
サブクエリの処理フローは前述の紹介の通りです。
記事一覧の成形をgetarticle_layout関数で行っています。
// 投稿IDをカンマで指定。
// [getarticle postid="123,123,123,123"]
function getarticle_func($atts, $content = null) {
extract(shortcode_atts(array(
'postid' => null,
), $atts));
/* postid取得 */
$array_postid = explode( ',', $postid );
$post_count = count($array_postid);
/* id設定 */
if(!empty($postid)) {
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => $post_count,
'order' => 'DESC',
'orderby' => 'date',
'post__in' => $array_postid,
);
} else {
//投稿IDの指定がない場合は最新4件取得
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 4,
);
}
//投稿取得
$query = new WP_Query( $args );
<div id="blog-entries">
<?php
// Loop through posts.
while ( $query->have_posts() ) {
getarticle_layout($query);
}
?>
</div><!-- #blog-entries -->
<?php
}
wp_reset_query();
}
add_shortcode('getarticle', 'getarticle_func');
/*
**
** レイアウト生成
**
*/
function getarticle_layout($query) {
$query->the_post();
// Get post entry content.
$post_id = $query->posts[0]->ID;
$post_date = date("Y年h月j日",strtotime($query->posts[0]->post_date));
$post_title = $query->posts[0]->post_title;
$img_args = array(
'alt' => $post_title,
);
?>
<article id="post-<?php echo $post_id; ?>">
<a href="<?php echo the_permalink(); ?>">
<div class="archive-thumbnail">
<?php echo the_post_thumbnail( 'full', $img_args ); ?>
</div>
<div class="archive-entry-content">
<div class="archive-entry-time">
<?php echo $post_date; ?>
</div>
<h5 class="archive-entry-title">
<?php echo the_title(); ?>
</h5>
</div>
</a>
</article>
<?php
}
※あくまで、サブクエリの取得イメージなので、CSSはありません。