How to get latest post ID in functions.php?

Here is the code that should probably work for you:

function bt_update_user_homepage_meta() {

    // Get user id
    $user_id = get_current_user_id();

    if ( !empty( $user_id ) && is_page( [ 'home' ] ) ) {

        $posts = wp_get_recent_posts( array(
            'numberposts' => 1,
            'meta_key'    => 'usp-custom-1',
            'meta_value'  => 'question'
        ) );

        if ( !empty( $posts ) ) {
            update_user_meta( $user_id, 'pagehome', array_pop( $posts )->ID );
        }
    }
}

add_action( 'wp', 'bt_update_user_homepage_meta' );

I’ve tweaked things:

  • I’ve wrapped it up in the if ( !empty( $user_id ) && is_page( [ 'home' ] ) ) so that you don’t do any of this processing unless the user is logged-in and it’s the page “home”
  • I use the handy wp lookup function wp_get_recent_posts for recent posts that orders them by the newest published, and limit the query to 1 result.
  • then I pop it off the array of posts and reference the ID to store it into the user meta.

For completeness sake, I should say that you probably shouldn’t be doing this on every time the page is loaded as you’ll have that extra get_posts() query each time, albeit for only logged-in users. There isn’t really an issue with updating the user meta though, since if the value isn’t changed, no data is written to the DB.