0

I'm trying to fetch an array of all entries to a specific meta key and then check to see if the user input value exists in that array.

I've checked the data base for the query and I see the meta values.

I'm four days in and have learned a lot, about WP_Query, $wpdb, SQL and whole lot more and I feel like I understand what I'm writing fully but can't see where I am going wrong.

Any pointers in the right direction would be greatly appreciated.

Here's the code I've got to.

// process the checkout
add_action('woocommerce_checkout_process', 'jm_custom_checkout_field_process');

function jm_custom_checkout_field_process() {

        // Access the database 
        global $wpdb; 

        // query the database for array NOTE Have tried get_col
        $groupnames = $wpdb->get_results( " 
            SELECT *
            FROM $wpdb->postmeta
            WHERE 'meta_key' LIKE '_create_new_group'
            "
        ,OBJECT);

        // get value from user
        $newgroupname = $_POST['create_new_group'];

        // check if user input is in array
        if( in_array($newgroupname, $groupnames ) ) {
           wc_add_notice( __( 'Group name already taken.' ), 'error' );
        }
}

Update > Working Query

$meta_key = '_create_new_group';
$groupnames = $wpdb->get_col($wpdb->prepare("
    SELECT meta_value 
    FROM $wpdb->postmeta 
    WHERE meta_key = %s" 
    ,$meta_key
));
  • Why would you not just sanitize the $_POST value, then search for that in the db? – Jesse Pearson Dec 19 '14 at 0:26
  • The solution above is for the woocommerce checkout page. Woo already have functions, actions, filters and validation set-up, which includes sanitation and saving to the database. The above enabled me to work with everything built in. Hopefully that answers your question? If you have time would share an example of what you mean or direct me to a reference? – JohnMcCarthy Dec 19 '14 at 1:09
  • I think you've done what I was referring to, for the most part. I meant for you to query the db for what the user has posted, and if it comes back with a result, then you reject them and tell them the name is taken. If it has no result, then they can proceed. – Jesse Pearson Dec 22 '14 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.