$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Check if Post Title exists, Insert post if doesn't, Add Incremental # to Meta if does|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Check if Post Title exists, Insert post if doesn't, Add Incremental # to Meta if does

matteradmin8PV0评论

I already have a function where a user submits a form and creates a custom post...

<?php $postTitle = $_POST['post_title'];
$submit = $_POST['submit'];

if(isset($submit)){

    global $user_ID;

    $new_post = array(
        'post_title' => $postTitle,
        'post_content' => '',
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => '',
        'post_type' => 'stuff',
        'post_category' => array(0)
    );

    $post_id = wp_insert_post($new_post);
add_post_meta($post_id, 'times', '1');

}

I want to check if the custom-post title exists, then if it does NOT, to go ahead and create the post with a #1 in the meta field, and if it does exist, to simply add 1 to the meta field

I already have a function where a user submits a form and creates a custom post...

<?php $postTitle = $_POST['post_title'];
$submit = $_POST['submit'];

if(isset($submit)){

    global $user_ID;

    $new_post = array(
        'post_title' => $postTitle,
        'post_content' => '',
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => '',
        'post_type' => 'stuff',
        'post_category' => array(0)
    );

    $post_id = wp_insert_post($new_post);
add_post_meta($post_id, 'times', '1');

}

I want to check if the custom-post title exists, then if it does NOT, to go ahead and create the post with a #1 in the meta field, and if it does exist, to simply add 1 to the meta field

Share Improve this question asked Jul 15, 2012 at 18:58 marctainmarctain 5673 gold badges8 silver badges19 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 9

This would need a query.

So building on your code:

<?php
$postTitle = $_POST['post_title'];
$submit = $_POST['submit'];

if(isset($submit)){

    global $user_ID, $wpdb;

    $query = $wpdb->prepare(
        'SELECT ID FROM ' . $wpdb->posts . '
        WHERE post_title = %s
        AND post_type = \'stuff\'',
        $postTitle
    );
    $wpdb->query( $query );

    if ( $wpdb->num_rows ) {
        $post_id = $wpdb->get_var( $query );
        $meta = get_post_meta( $post_id, 'times', TRUE );
        $meta++;
        update_post_meta( $post_id, 'times', $meta );
    } else {
        $new_post = array(
            'post_title' => $postTitle,
            'post_content' => '',
            'post_status' => 'publish',
            'post_date' => date('Y-m-d H:i:s'),
            'post_author' => '',
            'post_type' => 'stuff',
            'post_category' => array(0)
        );

        $post_id = wp_insert_post($new_post);
        add_post_meta($post_id, 'times', '1');
    }
}

Should do it

A more updated method may use the post_exists() function like so:

if( isset( $_POST['submit'] ) ){

   $post_title = sanitize_title( $_POST['post_title'] );

   $new_post = array(
       'post_title' => $post_title,
       'post_content' => '',
       'post_status' => 'publish',
       'post_date' => date('Y-m-d H:i:s'),
       'post_author' => '',
       'post_type' => 'stuff',
       'post_category' => array(0)
   );

   $post_id = post_exists( $post_title ) or wp_insert_post( $new_post );

   update_post_meta( $post_id, 'times', '1' );

}

You can use the get_page_by_title() function of WordPress:

<?php $postTitle = $_POST['post_title'];
$submit = $_POST['submit'];


if(isset($submit)){
    $customPost = get_page_by_title($postTitle, OBJECT, 'stuff');

    if(!is_null($customPost)) {
       $meta = get_post_meta($customPost->ID, 'times', true);
       $meta++;
       update_post_meta($customPost->ID, 'times', $meta);

       return
    }

    global $user_ID;

    $new_post = array(
        'post_title' => $postTitle,
        'post_content' => '',
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => '',
        'post_type' => 'stuff',
        'post_category' => array(0)
    );

    $post_id = wp_insert_post($new_post);
    add_post_meta($post_id, 'times', '1');

}

@Tim Hallman nice answer. Use the function post_exists() to check post exist or not. More details visit https://developer.wordpress/reference/

You can do it by ID


$post_title = "This Awesome Title";
$post_content = "My content of something cool.";
$post_status = "publish"; //publish, draft, etc
$post_type = "page" // or whatever post type desired

/* Attempt to find post id by post name if it exists */
$found_post_title = get_page_by_title( $post_title, OBJECT, $post_type );
$found_post_id = $found_post_title->ID;

/**********************************************************
** Check If Page does not exist, if true, create a new post 
************************************************************/
if ( FALSE === get_post_status( $found_post_id ) ): 

      $post_args = array(
        'post_title' => $post_title,
        'post_type' => $post_type,
        'post_content'=> $post_content,
        'post_status'  => $post_status,
        //'post_author'  => get_current_user_id(),

        /* If you have meta fields to enter data into */ 
        'meta_input'   => array(
            'meta_key1' => 'my value',
            'meta_key2' => 'my other value',
        ),
      );      


      /* Add a new wp post into db, return it's post id */
      $returned_post_id = wp_insert_post( $post_args );  

      /* Update page template only if using "page" as the post_type */ 
      update_post_meta( $returned_post_id, '_wp_page_template', 'my-page-template.php' ); 

      /* Add values into meta fields. Work with ACF CUSTOM FIELDS!! */
      $field_key = "My_Field_KEY";
      $value = "my custom value";
      update_field( $field_key, $value, $returned_post_id );

      $field_key = "My_Other_Field_KEY";
      $value = "my other custom value";
      update_field( $field_key, $value, $returned_post_id );

      /* Save a checkbox or select value */
      // $field_key = "My_Field_KEY";
      // $value = array("red", "blue", "yellow");
      // update_field( $field_key, $value, $returned_post_id );

      /* Save to a repeater field value */
      // $field_key = "My_Field_KEY";
      // $value = array(
      //   array(
      //     "ss_name" => "Foo",
      //     "ss_type" => "Bar"
      //   )
      // );
      // update_field( $field_key, $value, $returned_post_id );

      /* Echo a response! */
      echo "<span class='pg-new'><strong>". $post_title . " Created!</strong></span><br>";
      echo "<a href='".esc_url( get_permalink($returned_post_id) )."' target='_Blank'>". $post_title . "</a><p>";


else:        
/***************************
** IF POST EXISTS, update it 
****************************/

      /* Update post */
      $update_post_args = array(
        'ID'           => $found_post_id,
        'post_title'   => $post_title,
        'post_content' => $post_content,
      );

      /* Update the post into the database */
      wp_update_post( $update_post_args );

      /* Update values into meta fields */
      $field_key = "My_Field_KEY";
      $value = "my custom value";
      update_field( $field_key, $value, $found_post_id );

      $field_key = "My_Other_Field_KEY";
      $value = "my other custom value";
      update_field( $field_key, $value, $found_post_id );

      /* Echo a response! */
      echo "<span class='pg-update'><strong>". $post_title . " Updated!</strong></span><br>"; 
      echo "<a href='".esc_url( get_permalink($found_post_id) )."' target='_Blank'>View</a> | <a href='post.php?post=".$found_post_id."&action=edit'>". $post_title . "</a><p>";

endif;

WordPress check if post exist by title

function wp_exist_post_by_title( $title ) {
    global $wpdb;
    $return = $wpdb->get_row( "SELECT ID FROM wp_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'post' ", 'ARRAY_N' );
    if( empty( $return ) ) {
        return false;
    } else {
        return true;
    }
}

// usage
if( wp_exist_post_by_title( $post->name ) ) {
// post exist
} else { 
// post does not exist
}
Post a comment

comment list (0)

  1. No comments so far