0
votes

Is it posssible to create a function that get the post_meta of a page based on the currentuser login and Page Title is a match?

So if user "Test1" is logged in it will get the post_meta of a Page that has the title "Test1". Only when there is a match, otherwise do nothing.

I got this function to retrieve the child of a parent and then load a field but when creating a new page there is no parent yet. That is why I want to create this new function.

function my_acf_load_field( $field ) {
    global $post;
    if ( 0 !== (int) $post->post_parent )
    {
         $some_value = get_post_meta( $post->post_parent, 'rwp_user_score', true );
        if ( ! empty ( $some_value ) )
            switch ( $field['name'] ) {
            case 'gemiddelde_score_hosting_provider':
            $field['value'] = '' . $some_value .'';
            break;
            }
    }
    return $field;
}

add_filter('acf/load_field', 'my_acf_load_field');
1

1 Answers

1
votes

You can use the get_page_by_title() function, coupled with wp_get_current_user() and do a check for is_user_logged_in() inside a custom function to either return false, or return the page meta you are looking for like this:

function get_user_based_page_meta() {
    //return false if user is not logged in
    if (!is_user_logged_in()) {
        return false;
    }

    //get current user login
    $user_login = wp_get_current_user()->user_login;

    //get page by title - will retun null if no page exists
    $page = get_page_by_title($user_login);

    //check if get_page_by_title was successful and then return meta value, else return false
    if ($page != null) {
        return get_post_meta($page->ID, 'gemiddelde_score_hosting_provider', true;
    } else {
        return false;
    }
}

You can then use this function inside whatever action/filter hook you are using like this:

$user_meta = get_user_based_page_meta();
if ($user_meta) {
    echo $user_meta;
} else {
    //do nothing - no user logged in, or no page with user_login as title found
}