hello I have this code snippet in function.php that actually I used a learnpress plugin hook for it:
learn-press/course-item-content
also I tried this one:
learn-press/lesson-start
and the goal is to have the number of learnpress lesson views for each lesson for guests and not logged in users.
I have created the custom field views for lp_lesson type with Pods plugin.
<?PHP
// I inserted this code to show the number of views for each lesson
//*************************************************************
add_action('learn-press/course-item-content', 'lesson_views');
function lesson_views(){
$item = LP_Global::course_item();
if(is_user_logged_in()){
$user = wp_get_current_user();
if ( !in_array( 'subscriber', (array) $user->roles ) ) {
return;
}
}
echo "<script>console.log('get_post_field".get_post_field('views',$item->get_id())."');
</script>";
$tempval = 0;
if(get_post_field('views',$item->get_id())==''||get_post_field('views',$item->get_id())==null)
{
$tempval = 1;
echo "<script>console.log('tempval = 1');</script>";
}
else
{
$tempval = intval(get_post_field('views',$item->get_id()))+1;
echo "<script>console.log('tempval = ".$tempval."');</script>";
}
update_post_meta($item->get_id(),'views',$tempval,get_post_field('views',$item->get_id()));
echo "<script>console.log('get_post_field".get_post_field('views',$item->get_id())."');
</script>";
//End Of the code to show the number of views for each lesson
//*************************************************************
}
add_action( 'updated_post_meta', 'my_update_post_meta', 10, 4 );
function my_update_post_meta($meta_id, $post_id, $meta_key, $_meta_value)
{
echo "<script>console.log('sth updated".$_meta_value."');</script>";
if($meta_key =="views"){
echo "<script>console.log('views updated".$_meta_value."');</script>";
}
}
I noticed that the update for the field views happens once, but when I refresh the page, it actually happened twice. for example if now the views=1 and I go to the page, it will be views=2, but after refresh the page, I understand the last value for views was not 2, but views=3! and now it will change to views=4. I checked if in the line that $tempval = intval(get_post_field('views',$item->get_id()))+1;
happens if I change the increasing value for example to 3, it will results that if views equals 1, and I go to the page and views updates to 4, but after that I go again to the page, the value is 7 at the start, and it will change to 10 and so on. I do not get it why this happens twice while I can not see any evidence that says this code happens twice. because the script codes that I put for check happens once, and the check in update hook proves it.