Home Forums General Issues wp_insert_post – check unique field


wp_insert_post – check unique field

  • Good afternoon.
    I’ll say right away – I’m only learning PHP and WordPress.
    I want to automatically add posts to my site using wp_insert_post, but with a check for uniqueness.
    Here is the standard code, in which there is an arbitrary unique_id field with the value 555555:

    $my_post = array(
      'post_title'    => 'test title',
      'post_content'  => 'test_post',
      'post_status'   => 'publish',
      'post_author'   => 1,
      'post_category' => array(50),
    	'meta_input' => array(
    		'unique_id' => '555555',
    // Insert the post into the database
    $post_id = wp_insert_post( $my_post );

    I want to make a check for the presence of this id in the post (ie if there is an id – update this post, and if there is no such id – add a new one).
    I tried to write post_id, but it doesn’t work.
    I will be grateful for your help.

  • You can run a query for the unique_id with the below:

    $existingPost = get_posts( array(
        'meta_key'   => 'unique_id',
        'meta_value' => '555555',
        $my_post['ID'] = $existingPost->ID;
        $post_id = wp_update_post( $my_post );
        $post_id = wp_insert_post( $my_post );
  • Thanks a lot. You helped me a lot!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.