Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Subscribe to RSS feed


Batch adding custom field to all posts in WordPress

Stanislav KhromovStanislav Khromov

The MySQL query below will add my-custom-field with value “hello” to all published posts.

INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT wp_posts.ID, 'my-custom-field', 0 FROM wp_posts WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type='hello';

Note
Fields that already have custom field my-custom-field will get another one. (So they will have 2 in total.)

Full-stack impostor syndrome sufferer & Software Engineer at Schibsted Media Group

Comments 1
  • Philipp
    Posted on

    Philipp Philipp

    Reply Author

    The query is doing something else:

    It inserts the custom field “my-custom-field” with value “0” to all custom posts with the post type “hello”.

    The correct query for the description would be:

    `
    INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
    SELECT wp_posts.ID, ‘my-custom-field’, ‘hello’
    FROM wp_posts
    WHERE wp_posts.post_status=’publish’ AND wp_posts.post_type=’post’;
    `