Snippets

Idoenk . Heri Purnomo Wordpress prevent duplicate post by its title

Created by Idoenk . Heri Purnomo last modified
<?php
function disallow_posts_with_same_title($post_id) {

  // If non-submission
  if (empty($_POST))
	return;
	
  // If this is just a revision, do nothing
  if ( wp_is_post_revision( $post_id ) )
    return;

  $post_title = get_the_title( $post_id );
  $args = [
	"post_type" => "post",
	"post_status" => "publish",
    "s" => $post_title,
  ];
  $query = get_posts( $args );
  $post_found = false;
  print_r($query); exit;

  // Delete current post on found query
  if (!empty($query)){
	foreach($query as $row){
	  if (strtolower($row->post_title) == strtolower($post_title)){
		$post_found = true;
		break;
	  }
	}

	// After double-check
	if ($post_found){

		// Send it to trash
		wp_delete_post($post_id);

		$redirect_to = get_site_url(null, 'wp-admin/edit.php');

		// In case of xmlrpc submission this routine is not needed.
		wp_redirect($redirect_to."?msg=duplicate", 301);
		exit;	
	}
  }
}
#add_action('post_updated_messages', 'disallow_posts_with_same_title');
//add_action('save_post', 'disallow_posts_with_same_title');
add_action('publish_post', 'disallow_posts_with_same_title');

function wpkatajokowi_admin_notice_error(){
  global $pagenow;
  if ( $pagenow == 'edit.php' && !empty($_GET["msg"]) && $_GET["msg"] == 'duplicate' ){
	  echo '<div class="error"><p>Your post is duplicate and has been trashed.</p></div>';
  }
}
add_action('admin_notices', 'wpkatajokowi_admin_notice_error');


Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.