Specifying meta field's column type in Database using add_post_meta

admin2025-06-02  2

In my code, I enhance one of my content types by following code:

add_post_meta( $post->ID, 'favourite_fruit_code', $value )

All goes well, but I would like to have power over specifying what a column type I would like to create in DB.

There are cases when we would need different DB column types would be appropriate - depending on data we are going to store. How can I specify this? (For example if I want my field to be stored in DB as TinyIntegerField, or BigIntegerField, etc.).

In my code, I enhance one of my content types by following code:

add_post_meta( $post->ID, 'favourite_fruit_code', $value )

All goes well, but I would like to have power over specifying what a column type I would like to create in DB.

There are cases when we would need different DB column types would be appropriate - depending on data we are going to store. How can I specify this? (For example if I want my field to be stored in DB as TinyIntegerField, or BigIntegerField, etc.).

Share Improve this question asked Feb 25, 2019 at 22:01 FusionFusion 1377 bronze badges 1
  • 1 Column type is LONGTEXT, you aren’t adding columns when you save data, just new rows. It’s somewhat moot anyway, what you get back from the engine will always be a string. – Milo Commented Feb 25, 2019 at 22:34
Add a comment  | 

1 Answer 1

Reset to default 2

When you use add_post_meta, no column in database is created. All post meta data is stored in wp_postmeta table (https://codex.wordpress/Database_Description#Table:_wp_postmeta). Here's the structure of that table:

  • post_id is the ID of post that this meta data is assigned to
  • meta_key is the key of meta (in your case favourite_fruit_code)
  • meta_value is the value of that meta

So you're not able to set the type of column, because there is no column, and you're not able to set the type of value, because all values are stored as LONGTEXT.

On the other hand, there is no need for setting the type of this column. You should sanitize and validate the values before setting them, and you can use meta_type in your meta query, so the values are compared correctly.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748865670a314368.html

最新回复(0)