这是在jQuery Ajax的帮助下始终可以做到的,并且get_page_by_title(\'About\', OBJECT, \'post\')
工具
基本上,您会监听标题字段上的更改,检查是否至少存在一篇标题相同的文章,如果没有,则启用提交按钮,否则会保持默认禁用状态(在页面加载时,该按钮会被禁用,直到进一步检查)。
add_action(\'wp_ajax_check-posts-by-title\', function(){
$title = isset( $_REQUEST[\'title\'] ) ? esc_attr( $_REQUEST[\'title\'] ) : null;
// check for title
if ( !$title ) {
return wp_send_json(array(
\'enable_btn\' => false,
\'message\' => \'No title specified!\'
));
}
$post = get_page_by_title($title, OBJECT, \'post\');
// check for post
if ( isset($post->ID) && \'publish\' === $post->post_status ) {
return wp_send_json(array(
\'enable_btn\' => false
));
}
// nothing caught
return wp_send_json(array(
\'enable_btn\' => true
));
// kill response
wp_die();
});
add_action(\'admin_footer\', function() {
global $pagenow;
if ( !$pagenow || !in_array($pagenow, array( \'post-new.php\' )) )
return; // only enqueue when writing/editing posts
?>
<script>
jQuery(document).ready(function($){
$(document).on("change", "#titlediv #title", function(e){
var i = $(this)
, f = i.closest(\'form\')
, t = i.val()
, b = $(\'input[name="publish"]\', f).first();
if ( self.xhr ) {
self.xhr.abort();
} else {
var xhr;
}
if ( !b.length ) return;
b.attr(\'disabled\',\'disabled\');
if ( $.trim( t ) ) {
self.xhr = $.ajax({type: \'post\', url: \'admin-ajax.php\', data: {
action: \'check-posts-by-title\',
title: t
}, success: function(res){
if ( res && res.enable_btn ) {
b.removeAttr(\'disabled\');
} else {
if ( res.message ) {
alert(res.message);
}
}
}, error: function(){
i.trigger(\'change\'); // roll over
}});
}
});
$(\'#titlediv #title\').trigger(\'change\');
});
</script>
<?php
});
希望这有帮助。