0

I am working on a wordpress site where users can submit there own posts. I would like to prevent users from adding a post with the same post_title

This is how i currently check to see if the post title exists:

$posts = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' OR post_status = 'trash' OR post_status = 'draft'");

gets the post title from the form

$alias = $_POST['post_title'];

checks if post_title is empty if it is create a random post_title else use the user defined one

if ($_POST['post_title'] == ''){
    $alias = generateRandomString();
} else {
    $alias = $_POST['post_title'];
}

I then check to see if the post_title already exists like this:

if (in_array($alias, $items)){
    echo '<p style="color:#fff">Sorry, That Title already exists!</p>';
} else {
//insert the post
}

My issue is that wordpress will add a number after the post title if it does already exist. Is there a way to prevent wordpress from doing this?

The output of the above above shows this:

Array ( [0] => db [1] => abi [2] => ybd [3] => cc [4] => cc-2 [5] => fb )

I need to prevent the cc-2 from happening.

1 Answer 1

0

I recently ran into a similar issue (rather tackling how to reset slugs that are dirty after importing). This is a snippit of the code I used to reset the slugs:

$wpdb->update( 
    $wpdb->posts, 
    array( 'post_name' => sanitize_title( $post_to_fix->post_title ) ), 
    array( 'ID' => $post_to_fix->ID ), 
    array( '%s' ), 
    array( '%d' ) 
);

Primarily focus on sanitize_title, where it sanitizes the post title and then saves to the post_name. I believe in your case if you were to query against the post_name instead of title you would have a better chance of handling nuances in the title and providing an accurate match. So here's a rough pass at what you might look at adding into your insert post check/add logic:

// check & set from a valid $_POST property or random string for a post name
$post_name = !empty($_POST['post_title']) ? generateRandomString() : $_POST['post_title'];

// filter by post type, note it can also take an array of post types
$post_type = 'post'; 

$get_post_args = array(
    'name' => $post_name,
    'post_type' => $post_type, 
    'post_status' => 'any',
    // get all posts
    'posts_per_page' => -1,
    // improve the performance of your query
    'fields' => 'ids',
    'no_found_rows' => true,
    'update_post_term_cache' => false,
    'update_post_meta_cache' => false
    );

$dup_posts_check = new WP_Query( $get_post_args );

if( !empty($dup_posts_check) ){
    echo '<p style="color:#fff">Sorry, That Title already exists!</p>';
} else {
    //insert the post
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.