こんな感じです。
記事投稿画面のカスタムフィールドに案件ID、開始時間、終了時間などを入力して蓄積していくと自動で所要時間を計算してくれて総作業時間を算出してくれるというものです。
<?php query_posts( $query_string . '&author_name=' . $user_name . '&meta_key=anken_id&meta_value=' . $id ); ?> <div class="column"> <p class="user"><?= $user_display_name; ?></p> <table width="100%" class="default" border="0" cellspacing="0" cellpadding ="5"> <tbody> <tr> <th width="8%" scope="col">日付</th> <th width="16%" scope="col">開始~終了 時間</th> <th width="8%" scope="col">所要時間</th> <th width="8%" scope="col">案件ID</th> <th width="30%" scope="col">クライアント/案件名</th> <th width="30%" scope="col">作業内容</th> </tr> <?php $work_time = array(); ?> <?php while( have_posts() ) : the_post(); ?> <?php //カスタムフィールドを取得 $cf = get_post_custom( $post->ID ); $anken_id = $cf['anken_id']; $work = $cf['work']; $etc = $cf['etc']; $start_time = $cf['start_time']; $end_time = $cf['end_time']; //投稿日を取得 $today = get_the_time( 'Y-m-d' ); //所要時間計算 $start = strtotime( $today . '.' . $start_time[0] ); $end = strtotime( $today . '.' . $end_time[0] ); $total = $end - $start; //所要時間を配列に追加 $work_time[] = $total; //所要時間を通常形式に変換 $total_time = date( 'H:i', $total ); ?> <tr> <td><?= $today; ?></td> <td><?= $start_time[0]; ?> ~ <?= $end_time[0]; ?></td> <td><?= $total_time; ?></td> <td><?= $anken_id[0]; ?></td> <td><?= get_the_title(); ?><br /><?= $work[0]; ?></td> <td><?= $etc[0]; ?></td> </tr> <?php endwhile; wp_reset_query(); ?> <?php //配列に入っている作業時間の和を求める $array_sum = array_sum( $work_time ); $work_time = date( 'H:i', $array_sum ); ?> </tbody> </table> <table width="100%" class="default" border="0" cellspacing="0" cellpadding ="5"> <tbody> <tr> <th width="20%" scope="row">合計作業時間</th> <td width="80%"><?= $work_time; ?></td> </tr> </tbody> </table> </div>
ミソ1 strtotimeで通常の時間表記とUnix timeに変換
strtotimeは引数に「年-月-日.時:分」を入れるとUNIXタイムに変換してくれる関数です。
Unixタイムとは1970年から現在までの秒数であるため、足し引き算で時間の計算が容易にできます。Unixタイムから通常の時間表記に直すにはdate関数を用います。
$start = strtotime( $today . '.' . $start_time[0] );
開始時刻と終了時刻のUNIXタイムを変数に入れたら、引き算で所要時間を求めます。
$total = $end - $start;
そしたらdate関数でUNIXタイムから通常の時間表記に戻します。
$total_time = date( 'H:i', $total );
ミソ2 配列に詰め込み、array_sumで全案件の所要時間の和を求める
ループの外で配列の初期化「$work_time = array();」を行い、ループ内で所要時間を配列に詰め込んで行きます。
$work_time[] = $total;
最後にループの外でarray_sum()で配列の数値の和を求めます。
$array_sum = array_sum( $work_time );
date()でUnixタイムを通常の時間表記に変換します。
$work_time = date( 'H:i', $array_sum );
- 関連記事
-
-
WordPress 投稿から任意の時間が経過した記事一覧を表示 2015/02/10
-
カスタムポストタイプに月別アーカイブを表示する wp_get_archives 2015/01/26
-
WordPressで日報システムのようなものを作ったので一部をメモ 2015/01/25
-
WordPress 固定ページに新着記事一覧を表示 2015/01/12
-
WordPress query_postsでページ送りが出来ない場合の対処法 2014/12/13
-