tableタグの見出しで昇順、降順の並び替えをする方法

この記事では、テーブルの列をクリックすると昇順・降順で並び替えできるHTML+JavaScriptの実装方法を紹介します。

1 実装のポイント

HTMLでテーブルを作成し、function.phpとJavaScriptでクリックイベントを設定するだけで、列ごとの昇順・降順ソートが可能です。CSSで見やすく調整しています。

2 HTMLコード


<div class="table-scroll-container" style="overflow-x:auto;">
  <table id="sortableTable" border="1" style="min-width:600px; border-collapse:collapse;">
    <thead>
      <tr>
        <th>名前</th>
        <th>年齢</th>
        <th>入社日</th>
      </tr>
    </thead>
    <tbody>
      <tr><td>山田太郎</td><td>32</td><td>2019-04-01</td></tr>
      <tr><td>鈴木花子</td><td>28</td><td>2021-07-15</td></tr>
      <tr><td>田中一郎</td><td>45</td><td>2010-10-10</td></tr>
      <tr><td>佐藤次郎</td><td>39</td><td>2015-06-20</td></tr>
    </tbody>
  </table>
</div>
  

3 functions.php にコードを追加


//---------------------------------------------
// テーブルの列をクリックすると昇順・降順で並び替え
//---------------------------------------------
$employees = [
    ['name'=>'山田太郎','age'=>32,'joined'=>'2019-04-01'],
    ['name'=>'鈴木花子','age'=>28,'joined'=>'2021-07-15'],
    ['name'=>'田中一郎','age'=>45,'joined'=>'2010-10-10'],
    ['name'=>'佐藤次郎','age'=>39,'joined'=>'2015-06-20'],
];

//sortable-table.jsを読み込む
function enqueue_sortable_table_script() {
    wp_enqueue_script(
        'sortable-table',
        get_stylesheet_directory_uri() . '/js/sortable-table.js',
        array(),
        '1.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_sortable_table_script');
  

4 javascript にコードを追加

ファイル名:sortable-table.js
保存先:wp-content/themes/child-theme/js/sortable-table.js


//---------------------------------------------
// テーブルの列をクリックすると昇順・降順で並び替え
//---------------------------------------------
document.addEventListener("DOMContentLoaded", function(){
  const table = document.getElementById("sortableTable");
  const headers = table.querySelectorAll("th");
  headers.forEach(th => {
    th.addEventListener("click", () => {
      const index = Array.from(th.parentNode.children).indexOf(th);
      const tbody = table.tBodies[0];
      const rows = Array.from(tbody.rows);
      const asc = th.dataset.asc !== "true";
      rows.sort((a,b) => {
        const aVal = a.cells[index].textContent.trim();
        const bVal = b.cells[index].textContent.trim();
        if(!isNaN(aVal) && !isNaN(bVal)){
          return asc ? aVal - bVal : bVal - aVal;
        } else {
          return asc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
        }
      });
      rows.forEach(row => tbody.appendChild(row));
      th.dataset.asc = asc;
    });
  });
});
  

4.1 ディレクトリ構造

  • child-theme/
    • style.css
    • functions.php
    • footer.php
    • header.php
    • js/
      • sortable-table.js
    • images/
      • logo.png

5 汎用CSS


/* --------------------------------------------
 * テーブルの列をクリックすると昇順・降順で並び替え
----------------------------------------------- */

body .blog-post table {
  width: 100%;
  border: 1px solid #ddd;
  border-collapse: collapse;
}
body .blog-post th, body .blog-post td {
  padding: 8px;
  text-align: left;
}
body .blog-post th {
  cursor: pointer;
  background-color: #f3f3f3;
}
  
補足:

  • 列のクリックで昇順・降順を切り替え可能です。
  • 数字や文字列、日付にも対応しています。
  • テーマに応じたCSSで見やすく調整しています。

6 完成イメージ

名前、年齢、入社日をクリックすると並び替えが出来ます。

名前 年齢 入社日
山田太郎 32 2019-04-01
鈴木花子 28 2021-07-15
田中一郎 45 2010-10-10
佐藤次郎 39 2015-06-20

7 まとめ

このコードを使えば、ブログ記事内で簡単に並び替え可能なテーブルを作成できます。PHPでデータを生成し、JavaScriptで並び替え、テーマごとのCSSで見やすく表示する流れです。