Site icon Hip-Hop Website Design and Development

get_post_meta returning empty string when data shows in the database

I’m absolutely stumped and I’m hoping this is something stupid that I just can’t see because I’m too close to it.

Working on an LMS using Sensei. Trying to get the course_id from a lesson. Pretty simple, it’s just meta data on a custom post type.

Cut everything down to this simple statement:

echo 'Course ID: ' . get_post_meta(17234, '_lesson_course', true);

I checked the database, the data is definitely there:

And there’s only one match.

But, it always just returns an empty string (or an empty array if I set the final argument to false).


Did some more digging. Found that my issue is my new function, but I don’t know why.

Here’s the entire mess:

function search_results_per_page( $query ) {
    echo 'Checking';
    if ( $query->is_search() ) {
        $accessible_post_ids = get_accessible_post_ids();
        $query->set('post__in', $accessible_post_ids);
    }
    return $query;
}
add_action( 'pre_get_posts',  'search_results_per_page'  );

function get_accessible_post_ids() {
    $allowed_posts = [];
    $user_id = get_current_user_id();
    $args = array('posts_per_page' => -1, 'post_type' => array('lesson', 'course', 'page'));
    $search_posts = new WP_Query($args);
    while($search_posts->have_posts()) {
        $search_posts->the_post();
        $post_type = get_post_type();
        $post_id = get_the_id();
        switch($post_type) {
            case 'lesson':
                echo 'Post ID: ' . $post_id;
                $course_id = get_post_meta($post_id, '_lesson_course', true);    
                echo ' Course ID: ' . $course_id . '<br>';
                if(sensei_has_user_started_course($course_id, $user_id)) {
                    $allowed_posts[] = $post_id;
                }
                break;
            case 'course':
                if(sensei_has_user_started_course($post_id, $user_id)) {
                    $allowed_posts[] = $post_id;
                }
                break;
            default:
                $allowed_posts[] = $post_id;
                break;
        }
    }
    wp_reset_postdata();
    return $allowed_posts;
}

For whatever reason, once I’m inside the while loop, get_post_meta no longer works. I sort of expected the while loop to fail, because it seems like it might be an infinitely re-occuring loop with the filter, but it seems to run. Just the get_post_meta returns an empty string.

Any brilliant thoughts out there?