WordPressで投稿した記事の本文を「more」で分割する方法

2601 Views
WordPress
WordPressで投稿した記事の本文を「more」で分割する方法

WordPressで広告を乗っけている方などは記事を投稿した際に「MORE」を入れることがあると思います。
その際に詳細ページなどでは「MORE」の部分に広告を入れたいなど思ったことはないでしょうか。

以下の方法ならデフォルトの投稿・カスタム投稿問わず実装することが可能です!

SNSでシェア♪

スポンサーリンク

目次

必要な情報は「$post_id」だけ!

おそらくこの関数を使用するのは一覧ページなどのアーカイブを作る時だと思います。
だいたいは以下のようなコードになると思います。

<?php
//アーカイブの表示
if (have_posts()) {
	while (have_posts()) {
		the_post();

		$title   = get_the_title();		//タイトル
		$content = get_the_content();	//本文

		echo "
			<article>
				<h1>{$title}</h1>
				<div class=\"clearFix\">
					{$content}
				</div>
			</article>
		";
	}
}
?>

そこでこのように増やしてあげてください。【7行目に追加あり】

<?php
//アーカイブの表示
if (have_posts()) {
	while (have_posts()) {
		the_post();

		$postID  = get_the_ID();		//記事ID
		$title   = get_the_title();		//タイトル
		$content = get_the_content();	//本文

		echo "
			<article>
				<h1>{$title}</h1>
				<div class=\"clearFix\">
					{$content}
				</div>
			</article>
		";
	}
}
?>

これで「$post_id」の準備は完了です。

 

functions.phpに以下のコードを追加

//投稿の本文をmoreの前後で分割する
function dividedContent($postID) {
	$getPost = get_post($postID);
	$content = $getPost->post_content;
	$regex   = '#(<p><span id="more-[\d]+"></span></p>|<span id="more-[\d]+"></span>|<!--more-->)#';

	//moreで分割
	if (preg_match($regex, $content)) {
		list($contentArray['before'], $contentArray['after']) = preg_split($regex, $content, 2);
	} else {
		$contentArray = array(
			'before' => $content,
			'after'  => ''
		);
	}
	return $contentArray;
}

簡単ですね。
あとは使い方です。

 

関数の使い方

先ほどのループの続きです。【9行目から追加あり】

<?php
//アーカイブの表示
if (have_posts()) {
	while (have_posts()) {
		the_post();

		$postID  = get_the_ID();		//記事ID
		$title   = get_the_title();		//タイトル

		$content = dividedContent($postID);	//moreで分割した本文を取得する

		echo "
			<article>
				<h1>{$title}</h1>
				<div class=\"clearFix\">
					{$content['before']}
				</div>
			</article>
		";
	}
}
?>

これだけです♪

 

あとがき

この方法であれば投稿・カスタム投稿問わず「MORE」で分割した本文を取得することが可能です!
広告を掲載するブログなどのサイトに役立てば幸いです。

SNSでシェア♪

スポンサーリンク

関連記事