Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Insert post metadata for all posts in CPT at once if metadata no existent

To anyone interested this is the query that worked for me:

INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value)
SELECT p.ID, 'score' AS meta_key, 0 AS meta_value
FROM $wpdb->posts AS p
WHERE p.post_type="my_cpt"
AND p.ID NOT IN (
    SELECT p2.ID 
    FROM $wpdb->posts AS p2
    INNER JOIN $wpdb->postmeta AS pm
    ON pm.post_id = p2.ID
    WHERE pm.meta_key = 'score'
)

But after reading this article I preferred to split the query in two for better performance:

global $wpdb;

//Get all posts which already have the metadata
$not_in = $wpdb->get_results( 
    "
    SELECT p.ID
    FROM $wpdb->posts AS p
    INNER JOIN $wpdb->postmeta AS pm
    ON pm.post_id = p.ID
    WHERE pm.meta_key = 'score'
    AND p.post_type="my-cpt"
    AND p.post_status NOT IN ('draft,auto-draft')",
    ARRAY_A
);

//Make results into string
$not_in = ! empty($not_in) ? implode( ',', array_column( $not_in, 'ID' ) ) : '';

//Insert new metadata
$wpdb->query(
    "
    INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value)
    SELECT p.ID, 'score' AS meta_key, 0 AS meta_value
    FROM $wpdb->posts AS p
    WHERE p.post_type="my-cpt"
    AND p.ID NOT IN ( $not_in )
    "
);

Related Posts:

  1. How to best delete orphan wp_postmeta
  2. wpdb custom post_type problem
  3. $wpdb: Counting posts corresponding to 3 terms in 3 different taxonomies
  4. Convert simple SQL Query to WordPress query
  5. $wpdb is queried but results don’t show
  6. Retrieve post data via WPDB class
  7. Create a WordPress Database query to find users who purchased specific product through WooCommerce [closed]
  8. Update Post Meta for a logged in user
  9. Getting meta in editor plugin, and event triggering issue
  10. How to duplicate entire custom post type
  11. A better way to add a meta box to custom post types
  12. Restrict Access to Posts based on Custom User and Post Meta Data
  13. Two Custom Post Types Many to Many Relationship
  14. get_post_meta not working on publishing
  15. Should wp_postmeta meta_key always be unique for a given post_id?
  16. how can I register a post_meta field in an existing CPT and then call it again with get_post_custom()?
  17. get_post_meta returning no value in custom post type alert email
  18. post meta parameter in post custom-post-type endpoint with restapi
  19. How do I set all of a particular post meta to a value within the custom post type I’m in?
  20. Update postmeta Parent when post_status child change
  21. Metabox not show in categories custom post type cmb2
  22. WordPress request fiter order by related post’s post_title
  23. Assign External Database Queries to Global Variables and Make Them Accessible
  24. How to import a custom MySQL DB table into a WordPress custom post type
  25. Update database from Quick Edit according to Checkbox state of Custom Post Type
  26. Custom fields (wp_post_meta) vs Custom Table for large amount of data
  27. Storing a many to many post type relationship in post meta and keeping SQL ability for Joins
  28. Get terms that contain posts that in turn belong to other terms?
  29. Function causing the loop display posting more (empty)
  30. Dynamic Custom Fields
  31. Show Custom Post Type meta boxes only on Page Edit
  32. Custom filter function not working with Custom post type
  33. wp_insert_post sometimes fails after API call
  34. Importing Data from a Non-WordPress database, into WP
  35. Getting thumbnails of a custom posts featured images in a page-templates metabox
  36. List Taxonomies: Don’t list taxonomy if it has no post – depending on custom post-meta?
  37. Remove Post Custom Meta Box
  38. Can’t publish custom post type – “You are not allowed to edit this post.”
  39. Save custom post type to external database
  40. Custom fields for custom post type
  41. Show future events based on custom field AND order by date
  42. Which is faster wpdb & get_row or wp_query & ge_post_meta?
  43. Meta Data for Custom Post Type not saving
  44. Using preg_replace to filter custom textarea
  45. $post not working working in AJAX plugin with custom post type
  46. Proper way to display latest 5 posts grouped by post type?
  47. Check if post with same meta value exists
  48. Filter date from post meta when date is in string format
  49. Get only used meta_values
  50. If Post Meta Equals Current Title Conditional Advanced Custom Fields
  51. Is there a way to exclude posts based on meta_values?
  52. Do posts, pages and / or custom post type objects have unique ID numbers or can there be multiple objects with the same IDs?
  53. Archieve.php not loading for custom post type
  54. Submitting Custom Post Types with custom fields from Front-end form
  55. create custom meta box with default value
  56. Get $post->ID from a URL
  57. Displaying a div from an assigned meta_value when on a page
  58. WPDB for post count on post
  59. Meta data (Tags and Categories) for Custom Posts not showing.
  60. Front end access to a SQL data repository – recommended way?
  61. Navigate posts with different post type that are in the same categories
  62. Display different information of a custom post type
  63. Create Array from custom post type to display a slider
  64. Setting Post Title via Meta Data returns Auto-draft
  65. How to Echo Metadata Value in Currency Format
  66. Issue on Working with Metabox – Checkbox to enable Sale Items
  67. Filter posts by tax (dropdown) and meta value
  68. delete_post_meta() for whole CPT / multiple posts?
  69. How to get specific post meta by title or id
  70. $wpdb->get_col and ORDER BY?
  71. Publish and save specific postmeta to a filtered post_type
  72. How to move a post to different post type with all meta data?
  73. Why do I have to press the “Update” button twice to save my meta box values?
  74. How can I display a drop-down select of Post Names
  75. how to show records that don’t have custom meta value
  76. WP API Response does not show my registered metadata
  77. How to detect that the save_post hook is calling the callback associated to the current edit post page only
  78. Update post if exist from PHP
  79. $post->post_meta not pulling any post in wordpress/php
  80. Values from meta-box not on $_POST
  81. WP_Query of custom post type sorted by meta_key has unexpected results
  82. Returning a custom content types with meta values
  83. Custom post type suddenly stoped working after WordPress 5 update
  84. Batch Extract Date from post title and put into ACF custom field
  85. copy images from custom field to another custom field
  86. How to show custom field on specific custom post type posts only when filled
  87. How to handle this specific case of custom post type?
  88. Save CTP post meta different values each day without overwriting previous values
  89. get_post_meta returns NULL in front-end, but correct result in back-end
  90. I’m trying to create a custom version of the wp_list_authors function that includes custom post types
  91. Cannot obtain custom meta information
  92. Problem with adding custom post type meta to header by plugin
  93. is_main_query() never called on WP 4.4
  94. How can I output WPAlchemy repeating fields meta values in my page template?
  95. Meta box data is saved but NOT displayed in the meta box text field. Why?
  96. How to call a post’s metadata in shortcode.php?
  97. New post from database
  98. Save Metabox Custom Field Value
  99. Echo custom post meta from options array
  100. Value of post meta dropdown is not showing in WordPress
Categories custom-post-types Tags custom-post-types, mysql, post-meta, wpdb
Proper way to implement/access a built-in page in my theme
Add Extra codes by plugin

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress