投稿記事の一覧をつくる

みなさん、自分のGitHubポートフォリオサイトに自分の投稿一覧を表示させてみたいと思ったことはありませんか?

この仕組みでは、REST APIという、ウェブ上でデータをやり取りするための標準的な方法を利用しています。REST APIを使うことで、ウェブサイトやアプリから、外部サービスのデータ(今回の場合は投稿一覧)を取得して表示することができます。

ただし、セキュリティ上の理由から「CORS(クロスオリジンリソースシェアリング)」という仕組みで、他のサイトからのデータ取得に制限がかかっています。そのため、現時点ではローカル環境(自分のPC上)でのみ動作し、GitHub Pagesなどの公開サイト上では表示できません。GitHub Pagesでの対応は、もう少しお待ちください 🙂

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>自分の記事だけを表示</title>
</head>
<body>
  <h2>自分が投稿した記事</h2>
  <div id="my-posts">Loading...</div>
  <script>
    // あなたのWordPressサイトのURL・ユーザーIDに置き換えてください
    const wpApiUrl = 'https://ideamarkets.info/wp-json/wp/v2/posts?author=10&per_page=5';

    fetch(wpApiUrl)
      .then(res => res.json())
      .then(posts => {
        if (!Array.isArray(posts) || posts.length === 0) {
          document.getElementById('my-posts').textContent = 'まだ記事がありません';
          return;
        }
        let html = '<ul>';
        posts.forEach(post => {
          html += `<li>
            <a href="${post.link}" target="_blank">${post.title.rendered}</a>
          </li>`;
        });
        html += '</ul>';
        document.getElementById('my-posts').innerHTML = html;
      })
      .catch(() => {
        document.getElementById('my-posts').textContent = '記事取得に失敗しました';
      });
  </script>
</body>
</html>

表示例

少し工夫すると本文の表示も可能になります。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>特定ユーザーの記事表示デモ</title>
  <style>
    body {
      font-family: "Segoe UI", "ヒラギノ角ゴ ProN W3", "Meiryo", sans-serif;
      background: #f9f9f9;
      margin: 0;
      padding: 2em;
    }
    h2 {
      color: #333;
    }
    #wp-posts ul {
      padding-left: 1.3em;
    }
    #wp-posts li {
      background: #fff;
      margin-bottom: 1.2em;
      padding: 1em;
      border-radius: 8px;
      box-shadow: 0 2px 6px #0001;
      list-style: disc inside;
    }
    #wp-posts img {
      border-radius: 6px;
      margin: 0.5em 0;
      display: block;
    }
    #wp-posts a {
      font-weight: bold;
      font-size: 1.12em;
      color: #2062af;
      text-decoration: none;
    }
    #wp-posts a:hover {
      text-decoration: underline;
    }
  </style>
</head>
<body>
  <h2>ユーザーID「3」の記事(5件)</h2>
  <div id="wp-posts">Loading...</div>
  <script>
    // ★「author=3」の部分を表示したいユーザーIDに変更してください
    const apiUrl = 'https://example.com/wp-json/wp/v2/posts?per_page=5&_embed&author=3';

    fetch(apiUrl)
      .then(res => res.json())
      .then(posts => {
        let html = '<ul>';
        posts.forEach(post => {
          const img = post._embedded && post._embedded['wp:featuredmedia']
            ? `<img src="${post._embedded['wp:featuredmedia'][0].source_url}" width="100">` : '';
          html += `<li>
            <a href="${post.link}" target="_blank">${post.title.rendered}</a><br>
            ${img}
            ${post.excerpt.rendered}
          </li>`;
        });
        html += '</ul>';
        document.getElementById('wp-posts').innerHTML = html;
      })
      .catch(() => {
        document.getElementById('wp-posts').textContent = '記事取得に失敗しました';
      });
  </script>
</body>
</html>