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

Create a random unique 6 digit number as custom field for custom post type

This quite an expensive operation what you are doing, and IMHO wrong worksflow as well. What you want to do is, is the following

  • Get all the meta_values from the specific meta_key you need.

  • You can then check the random number against the values returned from a specific meta_key

Here is a very basic idea in code: (Credit to Chinmoy Paul from pwdtechnology.com for the code. Code is commented for easy understanding)

The following goes into functions.php

/**    
 * Description: Getting all the values associated with a specific custom post meta key, across all posts
 * Author: Chinmoy Paul
 * Author URL: http://pwdtechnology.com
 *
 * @param string $key Post Meta Key.
 *
 * @param string $type Post Type. Default is post. You can pass custom post type here.
 *
 * @param string $status Post Status like Publish, draft, future etc. default is publish
 *
 * @return array
 */
function get_unique_post_meta_values( $key = '', $type="post", $status="publish" ) 
{
    global $wpdb;
    if( empty( $key ) )
        return;
    $res = $wpdb->get_col( 
        $wpdb->prepare( 
            "SELECT DISTINCT pm.meta_value 
            FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p 
            ON p.ID = pm.post_id
            WHERE pm.meta_key = '%s'
            AND p.post_status="%s"
            AND p.post_type="%s"", 
            $key, 
            $status, 
            $type 
        ) 
    );
    return $res;
}

Now, to get a specific array of meta values from a given meta_key from a specific post_type and post_status, you can try the following

// Get ids to exclude
$ids_to_exclude = get_unique_post_meta_values(
    'id', // This is our meta_key to get values from
    'MY_POST_TYPE', // This is the name of your custom post type
    'POST_STATUS' // Any other post status except publish as publish is default
);

/**
 * Generate a unique id
 * Thanks to Gautam3164 for the code
 * @see http://stackoverflow.com/a/17109530/1908141
 */
do {   
    // This is taken as is from your code in question
    $random   = substr( rand() * 900000 + 100000, 0, 6 );
} 
while( in_array( $random, $ids_to_exclude ) );
echo $random;

EDIT

You can put everything together in one fully functional function.

/**    
 * Description: Get a random unique 6 number id for any given meta_key
 *
 * @param string $key Post Meta Key.
 *
 * @param string $type Post Type. Default is post. You can pass custom post type here.
 *
 * @param string $status Post Status like Publish, draft, future etc. default is publish
 *
 * @return array
 */
function get_unique_random_value( 
    $key = '', 
    $type="post", 
    $status="publish" 
) {
    global $wpdb;

    // Check if we have a meta_key before continuing, if not, return false
    if( empty( $key ) )
        return false;

    $res = $wpdb->get_col( 
        $wpdb->prepare( 
            "SELECT DISTINCT pm.meta_value 
            FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p 
            ON p.ID = pm.post_id
            WHERE pm.meta_key = '%s'
            AND p.post_status="%s"
            AND p.post_type="%s"", 
            $key, 
            $status, 
            $type 
        ) 
    );
    // Check if we actually have an array of values, if not, return false
    if ( !$res )
        return false;

    /**
     * Generate a unique id
     * Thanks to Gautam3164 for the code
     * @see http://stackoverflow.com/a/17109530/1908141
     */
    do {   
        // This is taken as is from your code in question
        $random   = substr( rand() * 900000 + 100000, 0, 6 );
    } 
    while( in_array( $random, $res ) );
    return $random;
}

Then you can use it as follow

$random_id = get_unique_random_value (
    'id', // This is our meta_key to get values from
    'MY_POST_TYPE', // This is the name of your custom post type
    'POST_STATUS' // Any other post status except publish as publish is default
);
echo $random_id;

Related Posts:

  1. Meta Key Value in current-user-only loop
  2. get_post_meta not working on publishing
  3. Get data from PHP to JavaScript to set position of each post on front page
  4. when looping through custom post data not appearing
  5. Custom meta fields not showing up in WP_Response Object via custom endpoint
  6. WordPress loop add heading before first of type
  7. How to make a shortcode for my WP_Query Loop? [duplicate]
  8. get_post_meta for Custom Post Type ( CPT )
  9. Order by custom field attribute
  10. How do I filter a custom post type loop by a field?
  11. what is the correct way to compare dates in a WP query_posts meta_query
  12. Advanced search form with filters for custom taxonomies and custom fields
  13. Custom field values deleted when trashing custom post type
  14. How to get all custom fields of any post type
  15. Admin Area Custom Type Search By Meta Fields Without Title & Content
  16. How do I Paginate Search Results for Custom Post Types?
  17. Search that will look in custom field, post title and post content
  18. Display custom field of specific post where post title matches variable
  19. Conditional to modify query results
  20. get_template_part() – post-meta not working?
  21. wp_query to find posts by year and month
  22. Custom Post Type Taxonomies -Posts not showing in Category or Tag pages
  23. how to interconnect custom post types?
  24. How to insert content from another Custom Post type into Post?
  25. Using several custom fields as custom post title
  26. List all images from a single post meta value
  27. Very Slow Page – How to Optimize # of Queries?
  28. Populate Custom Fields in a Custom Post Type?
  29. WP_Query orderby modified to include custom meta changes
  30. Custom Post Type Loop throws 500 error when used in widget
  31. How to make sure content doesn’t display if selection is empty
  32. Two near-identical custom field types – one works, the other doesn’t . What can cause this?
  33. Calculate all custom field values in the post loop
  34. CPT + CMB2: data not displaying for only first post in loop
  35. How to check if user meta field is empty in conditional else statement
  36. Replace text in post from cvs
  37. How do i calculate the total of values of custom fields in custom post types?
  38. How to implement a Google map store locator
  39. I would like to have different styles for my posts based on the content of each post
  40. Checking if Post Title is Unique as Loop Criteria
  41. Query & Order posts by custom fields
  42. What is the recommended / best way to do this: Event calendar post/type in a block-based theme?
  43. Custom Tag Description unable to display just below and outside of the Loop
  44. Posting to a Custom Post Type from front end – user generated content
  45. Update Post Meta for a logged in user
  46. A better way to add a meta box to custom post types
  47. Two Custom Post Types Many to Many Relationship
  48. Store CPT ‘Reviews’ average ratings to a WordPress DB table or to a DB custom table?
  49. Using custom field content as expression in IF statement [closed]
  50. How do I set all of a particular post meta to a value within the custom post type I’m in?
  51. Custom fields (wp_post_meta) vs Custom Table for large amount of data
  52. Get post-meta value of all custom-posts – lowest to highest year-count?
  53. Add a meta field to the list of results for a custom post type
  54. Empty meta-box returns publishdate if no value is set?
  55. Custom PT, Taxonomys and wordpress query
  56. Need help with simple “if statement” checks to output particlular CPT data depending on what client uploads/fills out
  57. Displaying Posts Using a Custom Query with a Custom Field and a term_id
  58. How do I list a custom field and custom taxonomies for each result in a loop?
  59. How can i loop through custom post type according to custom meta field?
  60. Filter search posts by post meta?
  61. How can I increase the post count for custom post types only?
  62. How can I sort the order of multiple custom field values in a custom post type?
  63. Show the categories the current post has
  64. How do I ensure that post_type and Taxonomy use the same slug?
  65. Custom fields for post or terms which don’t update on post update
  66. Fetch data from two custom post types and create multidimensional array for output to html table
  67. Create an user checklist system for a course plateform using ACF Pro and ACF Extended
  68. Page that lists publications by classifying them by taxonomy
  69. CPT loop doesn’t seem to account for post date?
  70. How to sort WP_Query by a custom text field (written as a date dd/mm/yyyy)
  71. Custom Post Type meta data getting deleted on bulk editing taxonomies
  72. Custom fields array to display it monthly
  73. Alike Shortcode using in Custom Shortcode
  74. Query custom post type that has a serialized relational advanced custom field value
  75. Pagination not working in custom post type. Help
  76. Sort custom post column by generated value?
  77. Unable to gather Image URL from Custom Post Type’s; Custom Meta Field
  78. How to keep custom post type related information
  79. How to avoid duplicate posts queried from custom meta?
  80. How can I add a meta[] to my custom post type and search by term with the Rest API?
  81. Show posts from WP Custom Post Type selected from a field in a metabox
  82. Accessing download link from the loop with WP Download Manager Pro
  83. Custom Post Type has wrong label and is not found when called by a loop
  84. Creating an archive page or simple template to list all values of a custom field of specific post type listing
  85. Where is get_post_meta value located?
  86. Combine multiple separate lists into one
  87. Looping to organize and display custom posts by category using PHP and WordPress
  88. Get meta values from parent post and save in child post
  89. Adding a Section for Visitors
  90. How to Disable option of meta field if that option is selected for any other post in custom post type?
  91. Show parent category and subcategory once in while loop
  92. Stored meta from attachment, video length?
  93. WordPress trying to query two custom types to get child from the parent
  94. sorting in wp query based on custom field value
  95. PHP Notice: Unidentified index
  96. Custom taxonomy template for custom fields loop [closed]
  97. Add active class to foundation 6 tabs while looping categories
  98. Sort loop by custom field from different post type
  99. Display related post content and custom field content
  100. Add more custom fields when creating a new custom post type
Categories custom-post-types Tags custom-field, custom-post-types, loop, php, post-meta
$wp_customize->remove_section for customizer setting?
Get Pagination (WP-PageNavi) not to work

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