Get Meta Value for all Posts via $wpdb

I wrote a function which should give you the value of a meta key for all of the posts. I am not sure why my query is not working. It gives me an empty array as output when I var_dump the query. The value of the meta key is stored in array, so I am using unserialize to convert the mysql array to PHP array.

The Function

function wp_postquiz_total_completed_quizes_by_user( ) {

    global $wpdb;

    $mylink = $wpdb->get_results("
                        SELECT $wpdb->postmeta.meta_value * 
                        FROM $wpdb->postmeta 
                        WHERE $wpdb->postmeta.meta_key = '_pq_users_answered_quiz_on_post'",
                        ARRAY_A);


    $array = unserialize($mylink);

    return $array;
}

Related posts

1 comment

  1. There is a syntax error in your SELECT clause:

    SELECT $wpdb->postmeta.meta_value *
    

    It looks like you’re trying to select meta_value and “everything” even though meta_value is included in *. Do one or the other:

    SELECT $wpdb->postmeta.meta_value
    

    or

    SELECT *
    

    If the meta_value is the only field you’re interested in then the first one is the way to go. For future reference, you can get any SQL errors by calling:

    $wpdb->print_error();
    

Comments are closed.