Your global $new_job_count
won’t work unless the value is persisted somehow as the data only exists during the PHP process’ lifecycle and gets wiped when the process is done. To get the current count you need to do a query for example with WP_Query
.
To keep a track who, and when, has viewed the published posts trigger a Ajax (or WP REST API) call when the user clicks on the post count and save the current time to the user meta. This of course only works for logged in users. You’ll need to use a cookie or something for visitors.
The saved timestamp can then be used with the post count query to make it count only posts that have been published after the saved time.
For example something along these lines,
// functions
function my_user_last_new_jobs_check(int $user_id) {
return get_user_meta($user_id, 'new_jobs_checked', true);
}
function my_user_new_jobs_checked_now(int $user_id) {
return update_user_meta($user_id, 'new_jobs_checked', date('Y-m-d H:i:s'));
}
function my_get_new_jobs_count(int $user_id = 0) {
$args = [
'posts_per_page' => 500, // use some reasonable upper limit to prevent performance issues
'post_type' => 'job',
'post_status' => 'publish',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'fields' => 'ids',
];
$lastChecked = $user_id ? my_user_last_new_jobs_check($user_id) : ''; // maybe add default date & time as fallback
if ( $lastChecked ) {
$args['date_query'] = [
'after' => $lastChecked, // strtotime()-compatible string can be used here
];
}
$query = new WP_Query($args);
return $query->found_posts;
}
// template file
$newJobsCount = my_get_new_jobs_count(get_current_user_id());
echo $newJobsCount;
// ajax
add_action( 'wp_ajax_new_job_count_checked', 'my_ajax_callback' );
// add_action( 'wp_ajax_nopriv_new_job_count_checked', 'my_ajax_callback' );
function my_ajax_callback() {
// maybe validations, other checks, etc. here
$timestampSet = my_user_new_jobs_checked_now(get_current_user_id());
if ( $timestampSet ) {
wp_send_json_success();
} else {
wp_send_json_error();
}
}
N.B. Untested. Modify as needed.