1

I am saving posts by the current user's name. Furthermore, I am saving an array object - $ganalytics_settings - to the post in a custom field. With the following code I am trying to load the array for the username, with a specific post title:

    function get_custom_field_for_current_user( $customFieldName ) {

        $current_user = wp_get_current_user();          
        global $wpdb;
        $id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');

        return get_post_meta((int)$id[0], $customFieldName);
    }

However, I am getting back the following object:

enter image description here

Instead I would like to get back the following:

enter image description here

Any suggestions why my function gives me back an array in array?

I appreciate your reply!

2 Answers 2

1

I don't know if I understood you, but if your function returns the array with first key being an array, then just always return that first key

function get_custom_field_for_current_user( $customFieldName ) {

    $current_user = wp_get_current_user();
    global $wpdb;
    $id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');

    $post_meta = get_post_meta((int)$id[0], $customFieldName);

    return $post_meta[0];
}
Sign up to request clarification or add additional context in comments.

Comments

1

The function get_post_meta has the following signature get_post_meta ( int $post_id, string $key = '', bool $single = false ). The return value will be an array if $single is false. Will be value of meta data field if $single is true.

Try this:

function get_custom_field_for_current_user( $customFieldName ) {

    $current_user = wp_get_current_user();          
    global $wpdb;
    $id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $current_user->user_login . "' && post_status = 'draft' && post_type = 'post' ", 'ARRAY_N');

    return get_post_meta((int)$id[0], $customFieldName, true);
                                                      //^ Here to return single value
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.