Skip to content

Instantly share code, notes, and snippets.

@kurozumi

kurozumi/functions.php

Last active Aug 29, 2015
Embed
What would you like to do?
【ワードプレス】スラッグが重複していないかチェック
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