add_post_meta does not respect the content

I insert this and it works fine:

add_post_meta( get_the_ID(), 'robots', 'TEXT', true );

After adding that, I check the database and everything is fine, the result is TEXT.

But if I insert this:

add_post_meta( get_the_ID(), 'robots', 'a:2:{i:0;s:7:"noindex";i:1;s:8:"nofollow";}', true );

The result is:

s:43:"a:2:{i:0;s:7:"noindex";i:1;s:8:"nofollow";}";

And I need the result to be exactly the same as I have added it:

a:2:{i:0;s:7:"noindex";i:1;s:8:"nofollow";}

I need not to automatically add that s:43:” and the “; at the end.

Can anybody help me please?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Why the content is not being respected

And it’s not just add_post_meta(), but any functions like add_term_meta() and add_user_meta() that uses add_metadata().

And the reason why the value gets serialized again is because add_metadata() will automatically serialize the meta value using maybe_serialize() which (unfortunately) will serialize the value even if it’s already serialized.

How to tackle the issue

In your case, if possible, pass an array instead of the serialized value/string:

// A non-scalar value will be automatically serialized by maybe_serialize().
$value = array( 'noindex', 'nofollow' );

add_post_meta( get_the_ID(), 'robots', $value, true );

However, if you retrieved/received the value from somewhere and you need to retain its exact format when saving, then — as you’ve already figured it out — you’ll need to unserialize the value before passing it to add_post_meta() to prevent the double serialization.

But in WordPress, instead of using the native unserialize() function in PHP, I suggest you to use maybe_unserialize() instead:

$value = 'a:2:{i:0;s:7:"noindex";i:1;s:8:"nofollow";}';

// Unserialize the value and pass it to add_post_meta().
add_post_meta( get_the_ID(), 'robots', maybe_unserialize( $value ), true );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x