human_readable_duration()


WordPressのhuman_readable_duration()関数は、秒数を人間が読みやすい形式(例: “1時間30分”)に変換するために使用されます。

構文

human_readable_duration( int $seconds, bool $include_seconds = false );

引数の説明:

  • $seconds (int) — 変換する秒数を指定します。
  • $include_seconds (bool) — 秒数を含めるかどうかを指定します。デフォルトはfalseです。

例1: 基本的な使用例

この例では、3600秒を「1時間」に変換します。

<?php echo human_readable_duration(3600); ?>

例2: 秒数を含める

この例では、3665秒を「1時間1分5秒」に変換します。

<?php echo human_readable_duration(3665, true); ?>

例3: 投稿の公開時間を表示

この例では、投稿の公開時間を秒数に変換し、人間が読みやすい形式で表示します。

<?php $post_time = get_post_time('U', true); echo human_readable_duration(time() - $post_time); ?>

例4: カスタムフィールドの秒数を変換

この例では、カスタムフィールドから秒数を取得し、変換します。

<?php $seconds = get_post_meta(get_the_ID(), 'duration_seconds', true); echo human_readable_duration($seconds); ?>

例5: ショートコードでの使用

この例では、ショートコード内でhuman_readable_duration()を使用します。

function custom_duration_shortcode($atts) { $atts = shortcode_atts(array('seconds' => 0), $atts, 'duration'); return human_readable_duration($atts['seconds']); } add_shortcode('duration', 'custom_duration_shortcode');

例6: ウィジェットでの使用

この例では、ウィジェット内で秒数を変換して表示します。

function custom_duration_widget($seconds) { echo human_readable_duration($seconds); }

例7: カスタムクエリでの使用

この例では、カスタムクエリで取得したデータを変換します。

$query = new WP_Query(array('meta_key' => 'duration_seconds')); while ($query->have_posts()) { $query->the_post(); echo human_readable_duration(get_post_meta(get_the_ID(), 'duration_seconds', true)); }

例8: テーマファイルでの使用

この例では、テーマファイル内で秒数を変換して表示します。

$duration = 7200; echo human_readable_duration($duration);

注意点

  • 引数$secondsには正の整数を指定してください。
  • 秒数が非常に大きい場合、変換結果が長くなる可能性があります。

関連機能: