Wordpress - Check if Post Title exists, Insert post if doesn't, Add Incremental # to Meta if does
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' );
}
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
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');
}