0

So I wrote this little code snippet to add a post id along with the current users id to the user meta table. I'll use this to show the "lesson" posts that a user has viewed back to them.

My only concern with this way of doing it this way is that it seems Wordpress will have to loop through this whole table to retrieve these posts. What if there are tens of thousands of users (I'm being optimistic) and they all view on average 10 or 20 lessons? Could this cause performance issues? I don't know enough about databases yet to know. Is there maybe a better way to go about this that I'm missing?

<?php
if ( is_user_logged_in() ) {
    $user_ID = get_current_user_id();
    $post_ID = get_the_ID();
    add_user_meta( $user_ID, 'viewed_lesson_tracking', $post_ID ); // tracks that user has viewed the current post
}
?>

Thanks for your help!

1

Since there are going to be more than one post (lesson) per user, your code would be more like this:

<?php
if ( is_user_logged_in() ) {
    $user_ID = get_current_user_id();
    $post_ID = get_the_ID();
    $viewed = get_user_meta( $user_ID, 'viewed_lesson_tracking', true);
    if(empty($viewed)){
        $viewed = array();
    }
    $viewed[] = $post_ID
    add_user_meta( $user_ID, 'viewed_lesson_tracking', $viewed ); // tracks that user has viewed the current post
}
?>

So, all you have to do, when showing a list of all viewed lessons(posts) is to use the post__in parameter of WP_Query.

WordPress will not loop through the whole table. That's not how MySQL queries work. At any given time, there'll only be one query per user. You won't need to worry about the performance. Plus, WordPress caches all the queries and if you have a cache plugin on top of it, you don't need to even give it a thought.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.