-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_tracking.php
More file actions
1218 lines (1094 loc) · 45.3 KB
/
Copy pathtime_tracking.php
File metadata and controls
1218 lines (1094 loc) · 45.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Simple Time Tracking
* Plugin URI: https://capture.club/plugins/simple_time_tracker/
* Description: Simple time-tracking plugin with activity dropdown, date picker, and admin visualization and data aggregation.
* Version: 1.5.0
* Author: Kevin Cowan
* Author URI: https://kevinmcowan.com
* Text Domain: time-tracking-plugin
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Activation hook: create a "Log Time" page with form shortcode and "My Time Entries" page
*/
function ttp_activate_plugin() {
// Create "Log Time" page
$log_page_title = 'Log Time';
$log_page_content = '[time_entry_form]';
$log_page_check = get_page_by_title( $log_page_title, OBJECT, 'page' );
if ( ! $log_page_check ) {
$log_page_id = wp_insert_post( array(
'post_title' => $log_page_title,
'post_content' => $log_page_content,
'post_status' => 'publish',
'post_type' => 'page',
) );
if ( ! is_wp_error( $log_page_id ) ) {
update_option( 'ttp_time_entry_page_id', $log_page_id );
}
}
// Create "My Time Entries" page
$my_entries_title = 'My Time Entries';
$my_entries_content = '[my_time_entries]';
$my_entries_check = get_page_by_title( $my_entries_title, OBJECT, 'page' );
if ( ! $my_entries_check ) {
$my_entries_id = wp_insert_post( array(
'post_title' => $my_entries_title,
'post_content' => $my_entries_content,
'post_status' => 'publish',
'post_type' => 'page',
) );
if ( ! is_wp_error( $my_entries_id ) ) {
update_option( 'ttp_my_entries_page_id', $my_entries_id );
}
}
}
register_activation_hook( __FILE__, 'ttp_activate_plugin' );
/**
* Deactivation hook: optionally remove created pages
*/
function ttp_deactivate_plugin() {
$log_page_id = get_option( 'ttp_time_entry_page_id' );
if ( $log_page_id ) {
wp_delete_post( $log_page_id, true );
delete_option( 'ttp_time_entry_page_id' );
}
$my_entries_page_id = get_option( 'ttp_my_entries_page_id' );
if ( $my_entries_page_id ) {
wp_delete_post( $my_entries_page_id, true );
delete_option( 'ttp_my_entries_page_id' );
}
}
register_deactivation_hook( __FILE__, 'ttp_deactivate_plugin' );
/**
* Register the "time_entry" custom post type
*/
function ttp_register_time_entry_cpt() {
$labels = array(
'name' => __( 'Time Entries', 'time-tracking-plugin' ),
'singular_name' => __( 'Time Entry', 'time-tracking-plugin' ),
'menu_name' => __( 'Time Entries', 'time-tracking-plugin' ),
'name_admin_bar' => __( 'Time Entry', 'time-tracking-plugin' ),
);
$args = array(
'labels' => $labels,
'public' => false,
'show_ui' => false,
'capability_type' => 'post',
'supports' => array( 'title' ),
);
register_post_type( 'time_entry', $args );
}
add_action( 'init', 'ttp_register_time_entry_cpt' );
/**
* Enqueue jQuery UI Datepicker on the front-end
*/
function ttp_enqueue_frontend_scripts() {
if ( ! is_admin() ) {
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'jquery-ui-css', 'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css' );
$inline_js = "jQuery(function($){ $('#ttp_entry_date').datepicker({ dateFormat: 'yy-mm-dd' }); });";
wp_add_inline_script( 'jquery-ui-datepicker', $inline_js );
}
}
add_action( 'wp_enqueue_scripts', 'ttp_enqueue_frontend_scripts' );
/**
* Check if user is logged in when accessing time entry page and redirect if needed
*/
function ttp_check_login_redirect() {
// Only run on front-end
if ( is_admin() ) {
return;
}
// Check if we're on the time entry page
$time_entry_page_id = get_option( 'ttp_time_entry_page_id' );
if ( ! $time_entry_page_id || ! is_page( $time_entry_page_id ) ) {
return;
}
// If user is not logged in, redirect to login page
if ( ! is_user_logged_in() ) {
$current_url = home_url( add_query_arg( array(), $_SERVER['REQUEST_URI'] ) );
$login_url = wp_login_url( $current_url );
wp_redirect( $login_url );
exit;
}
}
add_action( 'template_redirect', 'ttp_check_login_redirect' );
/**
* Redirect users back to time entry page after login
*/
function ttp_login_redirect_filter( $redirect_to, $request, $user ) {
// Check if there's a redirect_to parameter and it contains our time entry page
if ( ! empty( $request ) ) {
$time_entry_page_id = get_option( 'ttp_time_entry_page_id' );
if ( $time_entry_page_id ) {
$time_entry_url = get_permalink( $time_entry_page_id );
// If the request URL matches our time entry page, redirect there
if ( strpos( $request, get_page_uri( $time_entry_page_id ) ) !== false ) {
return $time_entry_url;
}
}
}
// Default behavior
return $redirect_to;
}
add_filter( 'login_redirect', 'ttp_login_redirect_filter', 10, 3 );
/**
* Shortcode to display the front-end time entry form
* Usage: [time_entry_form]
*/
function ttp_time_entry_form_shortcode() {
// If user is not logged in, show login message
if ( ! is_user_logged_in() ) {
$current_url = get_permalink();
$login_url = wp_login_url( $current_url );
return '<p>' . sprintf(
__( 'Please <a href="%s">log in</a> to record time.', 'time-tracking-plugin' ),
esc_url( $login_url )
) . '</p>';
}
// Check for success message
$success_message = '';
$error_message = '';
if ( isset( $_GET['ttp_success'] ) && $_GET['ttp_success'] === '1' ) {
$entry_date = isset( $_GET['entry_date'] ) ? sanitize_text_field( $_GET['entry_date'] ) : '';
$activity = isset( $_GET['activity'] ) ? sanitize_text_field( $_GET['activity'] ) : '';
$hours = isset( $_GET['hours'] ) ? floatval( $_GET['hours'] ) : 0;
if ( $entry_date && $activity && $hours ) {
$success_message = '<div class="ttp-success-message">';
$success_message .= '<h3>' . esc_html__( 'Time Entry Saved Successfully!', 'time-tracking-plugin' ) . '</h3>';
$success_message .= '<p><strong>' . esc_html__( 'Entry Details:', 'time-tracking-plugin' ) . '</strong></p>';
$success_message .= '<ul>';
$success_message .= '<li><strong>' . esc_html__( 'Date:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $entry_date ) . '</li>';
$success_message .= '<li><strong>' . esc_html__( 'Activity:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $activity ) . '</li>';
$success_message .= '<li><strong>' . esc_html__( 'Hours:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $hours ) . '</li>';
$success_message .= '</ul>';
// Add link to view all entries
$my_entries_page_id = get_option( 'ttp_my_entries_page_id' );
if ( $my_entries_page_id ) {
$my_entries_url = get_permalink( $my_entries_page_id );
$success_message .= '<p><a href="' . esc_url( $my_entries_url ) . '" class="button">' . esc_html__( 'View My Time Entries', 'time-tracking-plugin' ) . '</a></p>';
}
$success_message .= '</div>';
}
} else {
// Check for error information
if ( isset( $_GET['ttp_error'] ) ) {
$error_code = sanitize_text_field( $_GET['ttp_error'] );
$error_details = isset( $_GET['error_details'] ) ? sanitize_text_field( $_GET['error_details'] ) : '';
$error_message = '<div class="ttp-error-message">';
$error_message .= '<h3>' . esc_html__( 'Error Saving Time Entry', 'time-tracking-plugin' ) . '</h3>';
switch ( $error_code ) {
case 'nonce_failed':
$error_message .= '<p>' . esc_html__( 'Security verification failed. Please try again.', 'time-tracking-plugin' ) . '</p>';
break;
case 'invalid_hours':
$error_message .= '<p>' . esc_html__( 'Invalid time value. Hours must be greater than 0.', 'time-tracking-plugin' ) . '</p>';
break;
case 'db_error':
$error_message .= '<p>' . esc_html__( 'Database error occurred while saving your entry.', 'time-tracking-plugin' ) . '</p>';
if ( $error_details && current_user_can( 'manage_options' ) ) {
$error_message .= '<p><strong>' . esc_html__( 'Technical details:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $error_details ) . '</p>';
}
break;
case 'missing_data':
$error_message .= '<p>' . esc_html__( 'Required fields are missing. Please fill in all required fields.', 'time-tracking-plugin' ) . '</p>';
break;
default:
$error_message .= '<p>' . esc_html__( 'An unknown error occurred. Please try again.', 'time-tracking-plugin' ) . '</p>';
if ( $error_details && current_user_can( 'manage_options' ) ) {
$error_message .= '<p><strong>' . esc_html__( 'Error code:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $error_code ) . '</p>';
$error_message .= '<p><strong>' . esc_html__( 'Details:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( $error_details ) . '</p>';
}
break;
}
$error_message .= '</div>';
}
}
$activities = array(
'Development',
'Meeting',
'Research',
'Design',
'Testing',
'Fundraising',
'Community Outreach',
'Event Planning',
'Volunteer Training',
'Maintenance',
'Administrative Work',
);
$activities[] = 'Other';
$date_default = date_i18n( 'Y-m-d' );
ob_start();
$img_url = plugin_dir_url( __FILE__ ) . 'assets/imgs/time_tracker_logo.png';
echo '<img src="' . esc_url( $img_url ) . '" alt="Time Tracker Logo" class="ttp-logo" />';
// Display success message if present
if ( $success_message ) {
echo $success_message;
}
// Display error message if present
if ( $error_message ) {
echo $error_message;
}
?>
<form method="post" class="ttp-form" >
<?php wp_nonce_field( 'ttp_time_entry', 'ttp_nonce' ); ?>
<p>
<label for="ttp_entry_date"><?php _e( 'Date:', 'time-tracking-plugin' ); ?></label>
<input type="text" name="ttp_entry_date" id="ttp_entry_date" value="<?php echo esc_attr( $date_default ); ?>" required>
</p>
<p>
<label for="ttp_activity"><?php _e( 'Activity:', 'time-tracking-plugin' ); ?></label>
<select name="ttp_activity" id="ttp_activity">
<?php foreach ( $activities as $activity ) : ?>
<option value="<?php echo esc_attr( $activity ); ?>"><?php echo esc_html( $activity ); ?></option>
<?php endforeach; ?>
</select>
</p>
<p id="ttp_activity_other_wrap" style="display:none;">
<label for="ttp_activity_other"><?php _e( 'Please specify:', 'time-tracking-plugin' ); ?></label>
<input type="text" name="ttp_activity_other" id="ttp_activity_other" maxlength="100" onblur="updateActivity()">
</p>
<p>
<label for="ttp_time_spent"><?php _e( 'Time (hours):', 'time-tracking-plugin' ); ?></label>
<input type="number" step="0.25" min="0.25" name="ttp_time_spent" id="ttp_time_spent" required>
</p>
<p>
<label for="ttp_notes"><?php _e( 'Notes (optional):', 'time-tracking-plugin' ); ?></label><br>
<textarea id="ttp_notes" name="ttp_notes" rows="3" cols="30"><?php echo esc_textarea( $_POST['ttp_notes'] ?? '' ); ?></textarea>
</p>
<p>
<button type="submit" name="ttp_submit"><?php esc_html_e( 'Log Time', 'time-tracking-plugin' ); ?></button>
</p>
</form>
<script>
function updateActivity(){
const activitySelect = document.getElementById('ttp_activity');
const otherInput = document.getElementById('ttp_activity_other');
if (activitySelect.value === 'Other' &&
otherInput.value.trim() !== '') {
const custom = otherInput.value.trim();
if (!custom) {
alert('Please specify an "Other" activity.');
otherInput.focus();
return false;
}
const newOption = new Option(custom, custom);
activitySelect.add(newOption);
activitySelect.value = newOption.value;;
}
return true;
}
jQuery(function($){
$('#ttp_activity').on('change', function(){
$('#ttp_activity_other_wrap').toggle( $(this).val() === 'Other' );
}).trigger('change');
});
document.addEventListener('DOMContentLoaded', function() {
// clear the form only if no success message is showing
<?php if ( ! isset( $_GET['ttp_success'] ) ): ?>
const form = document.querySelector('.ttp-form');
form.reset();
let notes = document.getElementById('ttp_notes');
notes.value = "";
<?php endif; ?>
});
</script>
<?php
return ob_get_clean();
}
add_shortcode( 'time_entry_form', 'ttp_time_entry_form_shortcode' );
/**
* Shortcode to display user's own time entries
* Usage: [my_time_entries]
*/
function ttp_my_time_entries_shortcode( $atts ) {
// If user is not logged in, show login message
if ( ! is_user_logged_in() ) {
$current_url = get_permalink();
$login_url = wp_login_url( $current_url );
return '<p>' . sprintf(
__( 'Please <a href="%s">log in</a> to view your time entries.', 'time-tracking-plugin' ),
esc_url( $login_url )
) . '</p>';
}
$atts = shortcode_atts( array(
'per_page' => 20,
'show_totals' => 'yes'
), $atts );
$current_user_id = get_current_user_id();
// Handle sorting parameters
$sort_by = isset( $_GET['sort_by'] ) ? sanitize_text_field( $_GET['sort_by'] ) : 'date';
$sort_order = isset( $_GET['sort_order'] ) ? sanitize_text_field( $_GET['sort_order'] ) : 'DESC';
// Build query for user's entries
$query_args = array(
'post_type' => 'time_entry',
'posts_per_page' => intval( $atts['per_page'] ),
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'user_id',
'value' => $current_user_id,
'compare' => '='
)
)
);
// Handle sorting
switch ( $sort_by ) {
case 'activity':
$query_args['meta_key'] = 'activity';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $sort_order;
break;
case 'hours':
$query_args['meta_key'] = 'time_spent';
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = $sort_order;
break;
case 'entry_date':
$query_args['meta_key'] = 'entry_date';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $sort_order;
break;
default:
$query_args['orderby'] = 'date';
$query_args['order'] = $sort_order;
break;
}
$user_entries = new WP_Query( $query_args );
ob_start();
// Display logo
$img_url = plugin_dir_url( __FILE__ ) . 'assets/imgs/time_tracker_logo.png';
echo '<img src="' . esc_url( $img_url ) . '" alt="Time Tracker Logo" class="ttp-logo" />';
echo '<div class="ttp-my-entries">';
echo '<h2>' . esc_html__( 'My Time Entries', 'time-tracking-plugin' ) . '</h2>';
// Show totals if enabled
if ( $atts['show_totals'] === 'yes' ) {
$total_query = new WP_Query( array(
'post_type' => 'time_entry',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'user_id',
'value' => $current_user_id,
'compare' => '='
)
)
) );
$total_hours = 0;
$activity_totals = array();
while ( $total_query->have_posts() ) {
$total_query->the_post();
$hours = floatval( get_post_meta( get_the_ID(), 'time_spent', true ) );
$activity = get_post_meta( get_the_ID(), 'activity', true );
$total_hours += $hours;
if ( ! isset( $activity_totals[ $activity ] ) ) {
$activity_totals[ $activity ] = 0;
}
$activity_totals[ $activity ] += $hours;
}
wp_reset_postdata();
echo '<div class="ttp-totals-summary">';
echo '<h3>' . esc_html__( 'Summary', 'time-tracking-plugin' ) . '</h3>';
echo '<p><strong>' . esc_html__( 'Total Hours Logged:', 'time-tracking-plugin' ) . '</strong> ' . esc_html( round( $total_hours, 2 ) ) . '</p>';
if ( ! empty( $activity_totals ) ) {
echo '<p><strong>' . esc_html__( 'By Activity:', 'time-tracking-plugin' ) . '</strong></p>';
echo '<ul class="ttp-activity-totals">';
arsort( $activity_totals );
foreach ( $activity_totals as $activity => $hours ) {
echo '<li>' . esc_html( $activity ) . ': ' . esc_html( round( $hours, 2 ) ) . ' ' . esc_html__( 'hours', 'time-tracking-plugin' ) . '</li>';
}
echo '</ul>';
}
echo '</div>';
}
// Sorting controls
echo '<div class="ttp-user-controls">';
echo '<form method="get" style="display: inline-block; margin-bottom: 15px;">';
// Preserve existing query parameters
foreach ( $_GET as $key => $value ) {
if ( ! in_array( $key, array( 'sort_by', 'sort_order' ) ) ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $value ) . '" />';
}
}
echo '<label for="user_sort_by">' . esc_html__( 'Sort by:', 'time-tracking-plugin' ) . '</label> ';
echo '<select name="sort_by" id="user_sort_by">';
echo '<option value="date"' . selected( $sort_by, 'date', false ) . '>' . esc_html__( 'Most Recent', 'time-tracking-plugin' ) . '</option>';
echo '<option value="entry_date"' . selected( $sort_by, 'entry_date', false ) . '>' . esc_html__( 'Entry Date', 'time-tracking-plugin' ) . '</option>';
echo '<option value="activity"' . selected( $sort_by, 'activity', false ) . '>' . esc_html__( 'Activity', 'time-tracking-plugin' ) . '</option>';
echo '<option value="hours"' . selected( $sort_by, 'hours', false ) . '>' . esc_html__( 'Hours', 'time-tracking-plugin' ) . '</option>';
echo '</select> ';
echo '<select name="sort_order">';
echo '<option value="DESC"' . selected( $sort_order, 'DESC', false ) . '>' . esc_html__( 'Descending', 'time-tracking-plugin' ) . '</option>';
echo '<option value="ASC"' . selected( $sort_order, 'ASC', false ) . '>' . esc_html__( 'Ascending', 'time-tracking-plugin' ) . '</option>';
echo '</select> ';
echo '<input type="submit" class="button" value="' . esc_attr__( 'Sort', 'time-tracking-plugin' ) . '" />';
echo '</form>';
echo '</div>';
// Entries table
if ( $user_entries->have_posts() ) {
echo '<table class="ttp-user-entries-table">';
echo '<thead>';
echo '<tr>';
echo '<th>' . esc_html__( 'Date', 'time-tracking-plugin' ) . '</th>';
echo '<th>' . esc_html__( 'Activity', 'time-tracking-plugin' ) . '</th>';
echo '<th>' . esc_html__( 'Hours', 'time-tracking-plugin' ) . '</th>';
echo '<th>' . esc_html__( 'Notes', 'time-tracking-plugin' ) . '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ( $user_entries->have_posts() ) {
$user_entries->the_post();
$entry_date = get_post_meta( get_the_ID(), 'entry_date', true );
$activity = get_post_meta( get_the_ID(), 'activity', true );
$hours = get_post_meta( get_the_ID(), 'time_spent', true );
$notes = get_post_meta( get_the_ID(), 'notes', true );
echo '<tr>';
echo '<td>' . esc_html( $entry_date ) . '</td>';
echo '<td>' . esc_html( $activity ) . '</td>';
echo '<td>' . esc_html( $hours ) . '</td>';
echo '<td>' . esc_html( $notes ) . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
// Pagination info
$total_entries = $user_entries->found_posts;
$showing_count = $user_entries->post_count;
if ( $total_entries > $showing_count ) {
echo '<p class="ttp-pagination-info">';
echo sprintf(
esc_html__( 'Showing %d of %d entries', 'time-tracking-plugin' ),
$showing_count,
$total_entries
);
echo '</p>';
}
} else {
echo '<p>' . esc_html__( 'No time entries found. Start by logging some time!', 'time-tracking-plugin' ) . '</p>';
$log_page_id = get_option( 'ttp_time_entry_page_id' );
if ( $log_page_id ) {
$log_page_url = get_permalink( $log_page_id );
echo '<p><a href="' . esc_url( $log_page_url ) . '" class="button">' . esc_html__( 'Log Time', 'time-tracking-plugin' ) . '</a></p>';
}
}
wp_reset_postdata();
echo '</div>';
return ob_get_clean();
}
add_shortcode( 'my_time_entries', 'ttp_my_time_entries_shortcode' );
/**
* Handle front-end form submission and save as a custom post
*/
function ttp_handle_time_entry_submission() {
// Security & auth checks - redirect if not logged in and trying to submit
if ( isset( $_POST['ttp_submit'] ) && ! is_user_logged_in() ) {
$time_entry_page_id = get_option( 'ttp_time_entry_page_id' );
if ( $time_entry_page_id ) {
$redirect_url = get_permalink( $time_entry_page_id );
$login_url = wp_login_url( $redirect_url );
wp_redirect( $login_url );
exit;
}
return;
}
if ( isset( $_POST['ttp_submit'] ) ) {
$current_url = home_url( add_query_arg( array(), $_SERVER['REQUEST_URI'] ) );
// Verify nonce
if ( ! wp_verify_nonce( $_POST['ttp_nonce'] ?? '', 'ttp_time_entry' ) ) {
$redirect_url = add_query_arg( array(
'ttp_error' => 'nonce_failed'
), $current_url );
wp_redirect( $redirect_url );
exit;
}
// sanitize inputs
$user_id = get_current_user_id();
$entry_date = sanitize_text_field($_POST['ttp_entry_date'] ?? '');
$activity = sanitize_text_field($_POST['ttp_activity'] ?? '');
$time_spent = floatval($_POST['ttp_time_spent'] ?? 0);
$notes = isset( $_POST['ttp_notes'] )
? sanitize_textarea_field( $_POST['ttp_notes'] )
: '';
// Validate required fields
if ( empty( $entry_date ) || empty( $activity ) || $time_spent <= 0 ) {
$error_details = '';
if ( empty( $entry_date ) ) $error_details .= 'Date is required. ';
if ( empty( $activity ) ) $error_details .= 'Activity is required. ';
if ( $time_spent <= 0 ) $error_details .= 'Hours must be greater than 0. ';
$redirect_url = add_query_arg( array(
'ttp_error' => $time_spent <= 0 ? 'invalid_hours' : 'missing_data',
'error_details' => urlencode( trim( $error_details ) )
), $current_url );
wp_redirect( $redirect_url );
exit;
}
// create the time_entry post
$post_id = wp_insert_post([
'post_type' => 'time_entry',
'post_title' => $entry_date . ' – ' . $activity,
'post_status' => 'publish',
]);
if ( is_wp_error( $post_id ) ) {
$redirect_url = add_query_arg( array(
'ttp_error' => 'db_error',
'error_details' => urlencode( $post_id->get_error_message() )
), $current_url );
wp_redirect( $redirect_url );
exit;
}
if ( $post_id ) {
update_post_meta($post_id, 'user_id', $user_id);
update_post_meta($post_id, 'entry_date', $entry_date);
update_post_meta($post_id, 'activity', $activity);
update_post_meta($post_id, 'time_spent', $time_spent);
update_post_meta($post_id, 'notes', $notes );
// Redirect with success parameters
$redirect_url = add_query_arg( array(
'ttp_success' => '1',
'entry_date' => urlencode( $entry_date ),
'activity' => urlencode( $activity ),
'hours' => $time_spent
), $current_url );
wp_redirect( $redirect_url );
exit;
} else {
$redirect_url = add_query_arg( array(
'ttp_error' => 'db_error',
'error_details' => urlencode( 'Failed to create post entry' )
), $current_url );
wp_redirect( $redirect_url );
exit;
}
}
}
add_action( 'init', 'ttp_handle_time_entry_submission' );
/**
* Add the "Time Tracking" admin menu page
*/
function ttp_add_admin_menu() {
add_menu_page(
__( 'Time Tracking', 'time-tracking-plugin' ),
__( 'Time Tracking', 'time-tracking-plugin' ),
'manage_options',
'time-tracking',
'ttp_admin_page_callback',
'dashicons-clock',
6
);
}
add_action( 'admin_menu', 'ttp_add_admin_menu' );
/**
* Handle CSV export
*/
function ttp_handle_csv_export() {
if ( ! isset( $_GET['ttp_action'] ) || $_GET['ttp_action'] !== 'export_csv' ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.', 'time-tracking-plugin' ) );
}
// Get sorting parameters
$sort_by = isset( $_GET['sort_by'] ) ? sanitize_text_field( $_GET['sort_by'] ) : 'date';
$sort_order = isset( $_GET['sort_order'] ) ? sanitize_text_field( $_GET['sort_order'] ) : 'DESC';
// Build query arguments
$query_args = array(
'post_type' => 'time_entry',
'posts_per_page' => -1,
'post_status' => 'publish'
);
// Handle sorting
switch ( $sort_by ) {
case 'user':
$query_args['meta_key'] = 'user_id';
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = $sort_order;
break;
case 'activity':
$query_args['meta_key'] = 'activity';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $sort_order;
break;
case 'hours':
$query_args['meta_key'] = 'time_spent';
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = $sort_order;
break;
case 'entry_date':
$query_args['meta_key'] = 'entry_date';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $sort_order;
break;
default:
$query_args['orderby'] = 'date';
$query_args['order'] = $sort_order;
break;
}
$entries = new WP_Query( $query_args );
// Set headers for CSV download
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment; filename="time-entries-' . date( 'Y-m-d' ) . '.csv"' );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
// Open output stream
$output = fopen( 'php://output', 'w' );
// Add CSV headers
fputcsv( $output, array(
__( 'Date', 'time-tracking-plugin' ),
__( 'User', 'time-tracking-plugin' ),
__( 'Activity', 'time-tracking-plugin' ),
__( 'Hours', 'time-tracking-plugin' ),
__( 'Notes', 'time-tracking-plugin' ),
__( 'Created', 'time-tracking-plugin' )
) );
// Add data rows
if ( $entries->have_posts() ) {
while ( $entries->have_posts() ) {
$entries->the_post();
$post_id = get_the_ID();
$user_id = get_post_meta( $post_id, 'user_id', true );
$user = get_userdata( $user_id );
$user_name = $user ? $user->display_name : __( 'Unknown User', 'time-tracking-plugin' );
fputcsv( $output, array(
get_post_meta( $post_id, 'entry_date', true ),
$user_name,
get_post_meta( $post_id, 'activity', true ),
get_post_meta( $post_id, 'time_spent', true ),
get_post_meta( $post_id, 'notes', true ),
get_the_date( 'Y-m-d H:i:s' )
) );
}
}
wp_reset_postdata();
fclose( $output );
exit;
}
add_action( 'admin_init', 'ttp_handle_csv_export' );
/**
* Enqueue Chart.js on the admin page
*/
function ttp_enqueue_admin_scripts( $hook ) {
if ( $hook !== 'toplevel_page_time-tracking' ) {
return;
}
wp_enqueue_script( 'chartjs', 'https://cdn.jsdelivr.net/npm/chart.js', array(), '3.9.1', true );
// Add admin styles for sorting and export
wp_add_inline_style( 'wp-admin', '
.ttp-controls {
margin: 20px 0;
padding: 15px;
background: #f1f1f1;
border-radius: 5px;
}
.ttp-controls label {
margin-right: 10px;
font-weight: bold;
}
.ttp-controls select, .ttp-controls .button {
margin-right: 15px;
}
.ttp-sortable th {
cursor: pointer;
position: relative;
}
.ttp-sortable th:hover {
background-color: #f0f0f1;
}
.ttp-sortable th.sorted-asc::after {
content: " ↑";
color: #0073aa;
}
.ttp-sortable th.sorted-desc::after {
content: " ↓";
color: #0073aa;
}
' );
}
add_action( 'admin_enqueue_scripts', 'ttp_enqueue_admin_scripts' );
/**
* Render the admin page: chart + recent entries table
*/
function ttp_admin_page_callback() {
echo "<style>";
echo '.ttp-logo { ';
//echo ' background: url(' ../images / logo . png') no-repeat center;\n';
echo 'width: 25%;';
//echo 'height: 100px;';
echo '}';
echo "</style>";
$img_url = plugin_dir_url( __FILE__ ) . 'assets/imgs/time_tracker_logo.png';
echo '<img src="' . esc_url( $img_url ) . '" alt="Time Tracker Logo" class="ttp-logo" />';
echo '<div class="wrap"><h1>' . esc_html__( 'Time Tracking Summary', 'time-tracking-plugin' ) . '</h1>';
echo '<p>' . esc_html__( 'Use this plugin to allow your team to log hours against predefined activities and review summaries in the admin.', 'time-tracking-plugin' ) . '</p>';
echo '<h2>' . esc_html__( 'Front-end Usage', 'time-tracking-plugin' ) . '</h2>';
echo '<ul>';
echo '<li>' . esc_html__( 'Authentication required: only logged-in users can submit entries.', 'time-tracking-plugin' ) . '</li>';
echo '<li>' . esc_html__( 'Shortcode: add [time_entry_form] to any page.', 'time-tracking-plugin' ) . '</li>';
echo '<li>' . esc_html__( 'User entries: add [my_time_entries] to show individual user summaries.', 'time-tracking-plugin' ) . '</li>';
echo '<li>' . esc_html__( 'Date picker, activity dropdown, and hours input included.', 'time-tracking-plugin' ) . '</li>';
echo '</ul>';
echo '<h2>' . esc_html__( 'Admin Interface', 'time-tracking-plugin' ) . '</h2>';
echo '<ul>';
echo '<li>' . esc_html__( 'Summary chart: aggregate hours per activity.', 'time-tracking-plugin' ) . '</li>';
echo '<li>' . esc_html__( 'Recent entries: view last 10 submissions.', 'time-tracking-plugin' ) . '</li>';
echo '<li>' . esc_html__( 'Plugin creates "Log Time" and "My Time Entries" pages on activation.', 'time-tracking-plugin' ) . '</li>';
echo '</ul>';
echo '</div>';
// Query and aggregate
$query = new WP_Query(array('post_type'=>'time_entry','posts_per_page'=>-1,'post_status'=>'publish'));
$data = array();
while($query->have_posts()){ $query->the_post();
$act = get_post_meta(get_the_ID(),'activity',true);
$hrs = floatval(get_post_meta(get_the_ID(),'time_spent',true));
$data[$act] = (!isset($data[$act])?0: $data[$act]) + $hrs;
}
wp_reset_postdata();
$labels = json_encode(array_keys($data));
$values = json_encode(array_values($data));
?>
<canvas id="ttpTimeChart" width="400" height="200"></canvas>
<?php
// Get current sorting parameters
$current_sort = isset( $_GET['sort_by'] ) ? sanitize_text_field( $_GET['sort_by'] ) : 'date';
$current_order = isset( $_GET['sort_order'] ) ? sanitize_text_field( $_GET['sort_order'] ) : 'DESC';
?>
<div class="ttp-controls">
<form method="get" style="display: inline-block;">
<input type="hidden" name="page" value="time-tracking" />
<label for="sort_by"><?php _e( 'Sort by:', 'time-tracking-plugin' ); ?></label>
<select name="sort_by" id="sort_by">
<option value="date" <?php selected( $current_sort, 'date' ); ?>><?php _e( 'Created Date', 'time-tracking-plugin' ); ?></option>
<option value="entry_date" <?php selected( $current_sort, 'entry_date' ); ?>><?php _e( 'Entry Date', 'time-tracking-plugin' ); ?></option>
<option value="user" <?php selected( $current_sort, 'user' ); ?>><?php _e( 'User', 'time-tracking-plugin' ); ?></option>
<option value="activity" <?php selected( $current_sort, 'activity' ); ?>><?php _e( 'Activity', 'time-tracking-plugin' ); ?></option>
<option value="hours" <?php selected( $current_sort, 'hours' ); ?>><?php _e( 'Hours', 'time-tracking-plugin' ); ?></option>
</select>
<label for="sort_order"><?php _e( 'Order:', 'time-tracking-plugin' ); ?></label>
<select name="sort_order" id="sort_order">
<option value="DESC" <?php selected( $current_order, 'DESC' ); ?>><?php _e( 'Descending', 'time-tracking-plugin' ); ?></option>
<option value="ASC" <?php selected( $current_order, 'ASC' ); ?>><?php _e( 'Ascending', 'time-tracking-plugin' ); ?></option>
</select>
<input type="submit" class="button" value="<?php esc_attr_e( 'Sort', 'time-tracking-plugin' ); ?>" />
</form>
<a href="<?php echo esc_url( add_query_arg( array(
'ttp_action' => 'export_csv',
'sort_by' => $current_sort,
'sort_order' => $current_order
) ) ); ?>" class="button button-primary">
<?php _e( 'Export CSV', 'time-tracking-plugin' ); ?>
</a>
</div>
<h2><?php _e('Recent Entries', 'time-tracking-plugin'); ?></h2>
<table class="wp-list-table widefat fixed striped ttp-sortable">
<thead>
<tr>
<th class="<?php echo $current_sort === 'entry_date' ? 'sorted-' . strtolower($current_order) : ''; ?>">
<?php _e('Date','time-tracking-plugin'); ?>
</th>
<th class="<?php echo $current_sort === 'user' ? 'sorted-' . strtolower($current_order) : ''; ?>">
<?php _e('User','time-tracking-plugin'); ?>
</th>
<th class="<?php echo $current_sort === 'activity' ? 'sorted-' . strtolower($current_order) : ''; ?>">
<?php _e('Activity','time-tracking-plugin'); ?>
</th>
<th class="<?php echo $current_sort === 'hours' ? 'sorted-' . strtolower($current_order) : ''; ?>">
<?php _e('Hours','time-tracking-plugin'); ?>
</th>
<th><?php _e('Notes','time-tracking-plugin'); ?></th>
</tr>
</thead>
<tbody>
<?php
// Build query for sorted results
$query_args = array(
'post_type' => 'time_entry',
'posts_per_page' => 25, // Show more entries when sorted
'post_status' => 'publish'
);
// Handle sorting
switch ( $current_sort ) {
case 'user':
$query_args['meta_key'] = 'user_id';
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = $current_order;
break;
case 'activity':
$query_args['meta_key'] = 'activity';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $current_order;
break;
case 'hours':
$query_args['meta_key'] = 'time_spent';
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = $current_order;
break;
case 'entry_date':
$query_args['meta_key'] = 'entry_date';
$query_args['orderby'] = 'meta_value';
$query_args['order'] = $current_order;
break;
default:
$query_args['orderby'] = 'date';
$query_args['order'] = $current_order;
break;
}
$recent = new WP_Query( $query_args );
if($recent->have_posts()): while($recent->have_posts()): $recent->the_post();
$date = get_post_meta(get_the_ID(),'entry_date',true);
$user = get_userdata(get_post_meta(get_the_ID(),'user_id',true));
$act = get_post_meta(get_the_ID(),'activity',true);
$hrs = get_post_meta(get_the_ID(),'time_spent',true);
$notes = get_post_meta(get_the_ID(),'notes',true);
echo '<tr><td>'.esc_html($date).'</td><td>'.esc_html($user->display_name).'</td><td>'.esc_html($act).'</td><td>'.esc_html($hrs).'</td><td>'.esc_html($notes).'</td></tr>';
endwhile; else:
echo '<tr><td colspan="5">'.__('No entries found.','time-tracking-plugin').'</td></tr>';
endif;
wp_reset_postdata();
?>
</tbody>
</table>
<br/><hr/>
<h2><?php _e('Activity Summary', 'time-tracking-plugin'); ?></h2>
<?php echo ttp_render_time_rollup_table(); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
const ctx = document.getElementById('ttpTimeChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: <?php echo $labels; ?>,
datasets: [{
label: <?php echo wp_json_encode( __( 'Hours', 'time-tracking-plugin' ) ); ?>,
data: <?php echo $values; ?>
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: <?php echo wp_json_encode( __( 'Hours', 'time-tracking-plugin' ) ); ?>
}
}
}
}
});
});
</script>
<?php
echo '</div>';
}
function ttp_enqueue_frontend_assets() {