0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【WordPress】投稿内の内部リンク一覧を好きな箇所に自動出力する方法(SEOにもオススメ)

Last updated at Posted at 2023-02-28

WordPress投稿内の内部リンク一覧を取得して、リスト出力するショートコードの作成方法

ブログの記事内に設置した内部リンクを自動で取得して、記事の最後に一覧で見れるようにしたら回遊率が上がるかなと思い、試しに実装してみました。
あくまで私のブログだけのデータですが、実際にブログ内に導入したところ回遊率が上昇したので、試してみたいという方はどうぞご利用ください。

実際に筆者のブログで利用しているコードです。(コピペ可)

functions.php
// 内部リンクのリスト出力用ショートコード [my_shortcode_internal_links]
function my_internal_links() { 
	$content = get_the_content();
	$domain = $_SERVER['SERVER_NAME'];
	preg_match_all('/<a.+?href=".+'.$domain.'(?!.*#).*">.*<\/a>/', $content, $match);
	if($match):
		$match_unique = array_unique($match[0]);
		$html = '<section class="wp-block-post-content"><p>今回ご紹介した当ブログの記事はこちらです。</p><ul>';
		foreach ($match_unique as $link){
			$html .= '<li>'.$link.'</li>';
		}
		$html .= '</ul></section>';
		return $html;
	else:
		return;
	endif;
}
add_shortcode('my_shortcode_internal_links', 'my_internal_links');

実際の出力例を確認したい方は筆者ブログ【ギフテッドブログ】の記事本文末尾でご確認可能です。

重複したリンクは自動で1つにまとめており、テキストは投稿内のものをそのまま取得&出力しています。
HTML箇所はご自由に変更可能です。CSSは各々で設定してご利用ください。

上記コードはページ内リンク(#〜)が付いているリンクは除外して取得しております。
ページ内リンクも出力したい場合は下記内容に差し替えてご利用ください。

ページ内リンクも出力したい場合

functions.php
// ページ内リンクも出力したい場合は下に変更
-	 preg_match_all('/<a.+?href=".+'.$domain.'(?!.*#).*">.*<\/a>/', $content, $match);
+	 preg_match_all('/<a.+?href=".+'.$domain.'.*">.*<\/a>/', $content, $match);

下の行に差し替えるとページ内リンクもまとめて出力できるようになります。

利用方法

  1. functions.php に上記コードを貼り付け。
  2. テーマファイルの single.php または 投稿のブロックエディタ内に ショートコード [my_shortcode_internal_links] を貼り付け。

single.phpに貼り付ける場合は、ループ内に下記コードを貼り付けるとご利用できます。
<?php echo do_shortcode('[my_shortcode_internal_links]'); ?>

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?