0

I'm building a phone numbers directory website. Using wp_insert_post() visitors are allowed to add phone numbers without having to register or log in. There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code:

$post_id = wp_insert_post(array ( 'post_type' => 'numbers', 'post_title' => $name, 'post_content' => $details, 'post_status' => 'draft', 'tax_input' => $custom_tax, )); if ($post_id) { // insert post meta add_post_meta($post_id, 'number', $number); }

I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not.

If number already exists in database, user shouldn't be allowed to add it.

2 Answers 2

2

Try below code.

$args = array(
   'fields' => 'ids',
   'post_type'   => 'numbers',
   'meta_query'  => array(
     array(
     'key' => 'number',
     'value' => $number
     )
   )
 );
 $my_query = new WP_Query( $args );
 if( empty($my_query->have_posts()) ) {
   $post_id = wp_insert_post(array (
       'post_type' => 'numbers',
       'post_title' => $name,
       'post_content' => $details,
       'post_status' => 'draft',
       'tax_input' => $custom_tax,
   ));
   if ($post_id) {
       // insert post meta
       add_post_meta($post_id, 'number', $number);
   }
 }

If there is same number in postmeta it will not allow to create post and post meta.

Hope this will helps you.

0
1

Hi you can do it like that:

$post_id = wp_insert_post(array (
        'post_type' => 'numbers',
        'post_title' => $name,
        'post_content' => $details,
        'post_status' => 'draft',
        'tax_input' => $custom_tax,
    ));

if ($post_id) {
    $args = array(
       'post_type' => 'numbers',
       'meta_query' => array(
           array(
               'key' => 'number',
               'value' => $number
           )
       ),
       'fields' => 'ids'
     );
     // perform the query
     $number_query = new WP_Query( $args );

     $number_ids = $number_query->posts;

     // add number if the meta-key-value-pair does not exist in another post
     if ( empty( $number_ids ) ) {
         add_post_meta($post_id, 'number', $number);
     }
}

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.