0

How to add a custom field to my post when created programmatically?

I am trying to create a post programmatically, and store a value in a column created directly from PhpMyAdmin.

enter image description here

Here is how I am creating the post:

$post_title = $post->title->rendered;
$post_content = $post->content->rendered;

$post_check = get_page_by_title($post_title);
$post = array(
    'post_type' => 'post',
    'post_title' => $post_title,
    'post_content' => $post_content,
    'post_status' => 'publish',
    'post_author' => 1,
    'post_slug' => $post_title,
    'post_imported_id' => 3

);
$post_id = wp_insert_post($post);
if ($post_id) {
    add_post_meta( $post_id, 'post_imported_id', 3 );
}

The post is created and all default fields are well saved too.

The problem is that my "post_imported_id" is not taken in consideration.

2 Answers 2

2

You have created a custom field by altering the post table in the database. Custom fields in WordPress API are considered meta fields; such fields are stored in wp_postmeta table and that is the table used by functions like add_post_meta() and the rest of the functions and methods related with post custom/meta fields.

You can check how to work with meta/custom fields in the MetaData section of plugin developer handbook.

PD: Altering core database tables is considered a very bad practice.

1

When you use the add_post_meta() method, the custom post meta value will be stored automatically in the wp_postmeta table which has four columns: ID, post_id, meta_key and meta_value. So, in my opinion there is no reason for you to create an extra column manually and store your custom value there.

Later on, if you want to get the custom meta value for your post, just use the get_post_meta() method.

I hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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