WordPressショートコードで投稿データ表示。

テンプレート面倒くさくていじりたくない…。
新しいテンプレート作るときコピペするの面倒だもの…。

そこで、今更感抜群のこちら!

ショートコード内でテンプレートと同じ記事のループ処理をしてるので、
投稿内容がthe_content()とかdo_shortcode(get_the_content())を通ると記事が表示できます。

使い方としては、Magic Fields2プラグインでpost_typeとcustom_taxonomyいっぱい作って、
管理画面の編集できる範囲を固定化した後に、ページの本文でこのショートコードを呼び出して
一部の必要な記事を表示する。

ショートコード外の装飾はビジュアルエディタである程度いじれるのがメリット。

[show_posts post_type="posts" length="1"]

とかで管理画面から特定ポストタイプの最新の投稿1件を出せます。
あと、taxonomyも1個だけ対応している。
(ある固定ページにポストタイプ「event」の「交流会」タクソノミーの最新1件だけを表示したいときとかに)

[show_posts post_type="posts" taxonomy="post-tax"]

中ではWP_Queryでテンプレートに書くループやってるだけなので、後はスタイルシートで頑張る。

あと、ページ送りとか使わないような1件抽出とか向きです。そのへんまったく考慮してません。

あっ、中でloopテンプレート呼んだりしたほうがいいのかな?

<?php
function shortcode_show_posts($atts, $content = null){
 $result="";
//ショートコードで使えるオプションたち
 extract(shortcode_atts(array(
 'post_type'=>'',//ポストタイプ
 'post_id'=>'',//ポストID
 'length'=>1,//=posts_per_pages、記事数
 'taxonomy'=>'',//タクソノミー
 'order'=>'date',//ソート基準
 'orderby'=>'DESC',//ソート順
 'show_post_title'=>1,//タイトル表示するか?
 'show_post_date'=>1,//日付表示するか?
 'show_post_body'=>1,//本文表示するか?
 'use_link'=>0,//タイトルにパーマリンクするか?
 'title_class' => '',//タイトルに追加CSSクラス
 'body_class' => ''),//本文に追加CSSクラス
 $atts));

//WP_Queryに渡すオプションを整理
 if(!empty($taxonomy)){
//taxonomyがあるときは大体他の条件無視する。
 $opt=array(
 'tax_query'=>array(array('taxonomy'=>$post_type.'s', field=>'slug', terms=>array($taxonomy))),
 'posts_per_page'=>$length,
 'order'=>$order,
 'orderby'=>$orderby,
 'post_status' => 'publish'
 );
 }else{
 $opt=array(
 'post_type' => $post_type,
 'p'=>$post_id,
 'posts_per_page'=>$length,
 'order'=>$order,
 'orderby'=>$orderby,
 'post_status' => 'publish'
 );
 }

 $query = new WP_Query($opt);

 if($query->have_posts()):while($query->have_posts()):
 $result.='<div>';
 $query->the_post();

 if($show_post_title){
 $result.='<h3>';
 if($use_link){
 $result.='<a href="'.get_permalink().'">'.get_the_title().'</a>';
 }else{
 $result.=get_the_title();
 }
 $result.='</h3>';
 }

 if($show_post_date){
 $result.='<date>';
 $result.=get_the_date('Y年m月d日 H:i 掲載');
 $result.='</date>';
 }

 if($show_post_body){
 $result.='<div>';
 $content=do_shortcode(get_the_content());
 $result.=str_replace("\n","<br />",$content);
 }

 $result.='</div>';
 $result.='</div>';
 endwhile;endif;

 return $result;
}
add_shortcode("show_posts", "shortcode_show_posts");
?>

投稿者: あゆたや

札幌のWEB系の人です。バイトしながら個人制作も請けてます。一度寝たらなかなか起きません。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です