rtCamp notes, day 18 of undefined

What is Meta data?

Metadata can be termed as data of data or information of information,

it is the additional data we may add for our posts

How to add meta data?

We can use add_post_meta() to add meta data to database.

add_post_meta( int $post_id, string $meta_key, mixed $meta_value, bool $unique = false )

Here,

$post_id: ID of the post for which we should add meta data

$meta_key: name of the field for meta data

$meta_value: value of the metdata

$unique : whether the key must be unique

We can also update the previous meta data in the datbase by using the function

update_post_meta()
update_post_meta( int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )

Here,

$post_id: ID of the post for which we should add meta data

$meta_key: name of the field for meta data

$meta_value: value of the metdata

$prev_value : can use to check if the previous meta value is the same and will only update if it matches

Custom meta box

We can use add_meta_box() to add custom meta box to WordPress

add_action('add_meta_boxes', 'our_add_meta_function');

We should link it to the add_meta_boxes hook

To save the values we should add a callback function to check if our meta field are present at the time of saving the post.

Hook name: save_post

How to get meta values?

Use function : get_post_meta()

Leave a Reply

Your email address will not be published. Required fields are marked *