最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Specifying meta field's column type in Database using add_post_meta

matteradmin9PV0评论

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.

Post a comment

comment list (0)

  1. No comments so far