no-image

WordPressで記事内で別記事を表示する(get_the_contentする)ショートコード

記事をテンプレート化して他の記事内に入れたい時に使います。
functionsに以下のコードをコピペすればOK。

使い方は以下

[get_the_content id="記事番号" wpautop="trueかfalse defaultはfalse" shortcode="trueかfalse defaultはfalse"]

wpautopをtrueにすると、id指定した記事をWordpressデフォルトのpタグや改行で整形します。
shortcodeをtrueにすると、id指定した記事内にあるshortcodeも実行しますが、get_the_contentする先の記事にさらにget_the_contentが書かれていると記事同士でループし合ってしまう可能性があるので、十分注意して使用してください。

//shortycolossus////////////////////////////////
//  記事内でget_the_contentするショートコード
////////////////////////////////////////////////
add_shortcode('get_the_content', function($atts){
extract(shortcode_atts(array(
   'id' => null,'wpautop' => false,'shortcode' => false
),$atts));
global $wpdb;
$query = "SELECT ID,post_content FROM $wpdb->posts WHERE ID = ".$id." LIMIT 1;";
$wp_posts = $wpdb->get_results($query);
$content = $wp_posts[0]->post_content;
if ($wpautop) {
   $content = apply_filters('the_content', $content);
   $content = str_replace(']]>', ']]>', $content);
}
if ($shortcode) {
   $content = do_shortcode($content);
}
ob_start(); //これがないと投稿の一番上に表示されてしまう
echo $content;
return ob_get_clean();
});

pocketlinehatebuimagegalleryaudiovideocategorytagchatquotegoogleplusfacebookinstagramtwitterrsssearchenvelopeheartstaruserclosesearch-plushomeclockupdateeditshare-squarechevron-leftchevron-rightleafexclamation-trianglecalendarcommentthumb-tacklinknaviconasideangle-double-upangle-double-downangle-upangle-downstar-halfstatus