---
title: "Advanced Custom Fieldsで投稿記事に関連記事を紐づけて表示"
description: "タイトルままのミッション。 Advanced Custom Fieldsでまず記…"
url: "https://www.sensitivity.jp/wordpress/advanced-custom-fields%e3%81%a7%e6%8a%95%e7%a8%bf%e8%a8%98%e4%ba%8b%e3%81%ab%e9%96%a2%e9%80%a3%e8%a8%98%e4%ba%8b%e3%82%92%e7%b4%90%e3%81%a5%e3%81%91%e3%81%a6%e8%a1%a8%e7%a4%ba/"
canonical: "https://www.sensitivity.jp/wordpress/advanced-custom-fields%e3%81%a7%e6%8a%95%e7%a8%bf%e8%a8%98%e4%ba%8b%e3%81%ab%e9%96%a2%e9%80%a3%e8%a8%98%e4%ba%8b%e3%82%92%e7%b4%90%e3%81%a5%e3%81%91%e3%81%a6%e8%a1%a8%e7%a4%ba/"
date: "2020-06-29"
modified: "2020-06-29"
categories: ["WordPress"]
---

# Advanced Custom Fieldsで投稿記事に関連記事を紐づけて表示

タイトルままのミッション。

- Advanced Custom Fieldsでまず記事投稿画面で関連記事を拾えるように設定
- 投稿の際に関連記事を設定
- 表示の際に、関連記事を表示と、紐づいた記事の中にあるAdvanced Custom Fields内の情報も取得

と、いうことで、表示の際に行ったことについての 覚書メモです。

## 関連記事を出力するためのコード

```

<?php
 $post_object = get_field( 'フィールドの名前' );
 if( $posts ):
?>
<h1>関連記事</h1>
<ul>
<?php foreach( $post_object as $obj ): ?>
 <li>
  <h2><?php echo get_the_title( $obj->ID ); ?></h2>
  <a href="<?php echo get_permalink( $obj->ID ); ?>">くわしく見る</a>
 </li>
 <?php endforeach; ?>
</ul>
<php endif; ?>
```

### 取得した関連記事の中にあるカスタムフィールドの内容を表示する場合

```

<?php echo the_field( 'カスタムフィールド名', $obj->ID); ?>
```

ニュース系やコラム系のサイト構築ではこの仕組みを使うことが増えてきた。 頻度がそんなに多いわけではないが、あると便利機能かなと思う。

  [Advanced Custom Fields](https://www.advancedcustomfields.com/)

