Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/702ad73d73dfe331f858 to your computer and use it in GitHub Desktop.
Save kurozumi/702ad73d73dfe331f858 to your computer and use it in GitHub Desktop.
【ワードプレス】スラッグが重複していないかチェック
new WP_Check_Slug;
class WP_Check_Slug {
public function __construct()
{
add_action('admin_footer-post-new.php', array($this, 'admin_footer'));
add_action('admin_footer-post.php', array($this, 'admin_footer'));
add_action('wp_ajax_check-slug', array($this, 'check_slug'));
}
/**
* ポスト投稿時にスラッグチェックする
* @global type $hook_suffix
*/
public function admin_footer()
{
global $hook_suffix;
if ('post-new.php' === $hook_suffix || 'post.php' === $hook_suffix) {
?>
<script type="text/javascript">
document.getElementById('post_name').onchange = function () {
var post_name = document.getElementById('post_name').value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case 4:
if ((200 <= xhr.status && xhr.status < 300) || (xhr.status == 304)) {
var response = JSON.parse(xhr.response);
if (response.data.post_id > 0)
alert("登録済みのスラッグです。");
}
break;
}
};
xhr.open("POST", '<?php echo admin_url('admin-ajax.php'); ?>');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('action=check-slug&post_name=' + post_name);
return false;
};
</script>
<?php
}
}
public function check_slug()
{
$post = get_page_by_path($_POST['post_name'], OBJECT, 'post');
$post_ID = ($post) ? $post->ID : 0;
wp_send_json_success( array(
'post_id' => $post_ID
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment