Adding WordPress Post Metadata when using wp_insert_post

I found a little trick that I’ve overlooked so many times when writing plugins that use custom post types. Did you know that you can do this?

$args = [
    'post_type' => 'books',
    'post_title' => 'An Exciting Look at Mud',
    'post_content' => 'Things and stuff and content. Probably involving that book.',
    'meta_input' => [
        'book_author' => 'Mr. Bookwriter Dude',
        'authors_fav_quote' => "I have a belly button and HERE IT IS!"
    ]
];
$post_id = wp_insert_post($args);

How cool is that?! Now don’t laugh at me, but I looked for my postmeta in my DB because I’m always skeptical and look at this beauty:

mysql> select * from wp_postmeta where post_id=742444;
+---------+---------+-------------------+---------------------------------------+
| meta_id | post_id | meta_key          | meta_value                            |
+---------+---------+-------------------+---------------------------------------+
| 2779343 |  742444 | book_author       | Mr. Bookwriter Dude                   |
| 2779344 |  742444 | authors_fav_quote | I have a belly button and HERE IT IS! |
+---------+---------+-------------------+---------------------------------------+
2 rows in set (0.00 sec)

Nice 😎

Cheers!
Ryan

Leave a Reply

Rohjaynator::1656795910::2265781