0

I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table:

$order = new WC_Order( $order_id );
$items = $order->get_items();

$new_role = 'Array([advocate] => 1)';
$data = serialize( $new_role ); 

if ( $product_id == '786' ) {
    update_user_meta( $order->user_id, 'wp_capabilities', $data );
}

The correct table is being populated at the correct time but as

s:30:"s:22:"Array([advocate] => 1)";";

rather than what I need it to be which is

a:1:{s:8:"advocate";b:1;}

Where is my serialization tripping up?

0

I think you are not handling the array part correctly. The right syntax is -

$new_role = array("advocate" => 1);

The syntax that you have used is shown when you print some array on your screen but it should be written in above format in your PHP code. Currently, you are capturing it as a string and not an array.

  • Thanks @WisdmLabs, that's close: "s:25:"a:1:{s:8:"advocate";i:1;}";" ...but still not quite string I'm looking for. Is this a double-serialisation? – Kevin Nugent Sep 17 '14 at 17:32
  • Did you try it? I tried and it gave me a:1:{s:8:"advocate";i:1;} – WisdmLabs Sep 17 '14 at 17:40
  • Yeah, I tried it but got the output above with the double quotation marks and the extra s:25 and the start. Now using $new_role = array("advocate" => 1); $data = serialize( $new_role ); – Kevin Nugent Sep 17 '14 at 17:43
  • I found this thread which describes a similar issue but can't see how I might apply a fix to mine: stackoverflow.com/questions/22800132/… – Kevin Nugent Sep 17 '14 at 17:52
  • Have you tried saving the array without 'serialize'? Try it and see if it auto serialize when saving into the database. – WisdmLabs Sep 17 '14 at 18:11
0

In addition to syntax correction from WisdmLabs above I also found that I was effectively serialising the string TWICE as it will be automatically serialized when using update_user_meta. Not sure at which point I started serialising it myself but apparently that was completely unnecessary.

http://codex.wordpress.org/Function_Reference/update_user_meta

  • OK, you got it. – WisdmLabs Sep 17 '14 at 18:13
  • Yes, thanks for commenting anyway - got there in the end! – Kevin Nugent Sep 19 '14 at 7:30
0

The b in the serialized string means boolean. So you need to use true instead of one. And serializing it results in double serialization which explains "s:25:" in the beginning. Try this:

update_user_meta(46, 'wp_capabilities', array('employer'=>true));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.