我想问一个问题:我有一个源代码,它只适用于新帖子,但不适用于编辑帖子。那么,如果帖子标题存在,如何禁用编辑帖子上的发布按钮呢?
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
});
谢谢<;3.
SO网友:Tunji
您可以通过添加post.php 在脚本排队之前,先执行条件检查。
NOTE: 这可能会有效地禁用更新帖子的功能。
add_action(\'admin_footer\', function() {
global $pagenow;
if ( !$pagenow || !in_array($pagenow, array( \'post-new.php\', \'post.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
});