这就是我最终解决这个问题的原因。最初,我将此代码用于链接以删除单个帖子:
<?php if( !(get_post_status() == \'trash\') ) : ?>
<a class="delete-post" onclick="return confirm(\'Are you sure you wish to delete post: <?php echo get_the_title() ?>?\')"href="<?php echo get_delete_post_link( get_the_ID() ); ?>">Delete</a>
<?php endif; ?>
在检查用户是否已登录以及该用户是否是本文作者之后。这并没有像我在原来的帖子中提到的那样奏效。
相反,我使用了一个简单的删除按钮(与上面提到的检查相同):
<form class="delete-post" action="<?php bloginfo(\'url\'); ?>/edit-post" method="post">
<input id="post_id" type="hidden" name="postid" value="<?php the_ID(); ?>" />
<input type="submit" value="Delete" />
</form>
这个jQuery脚本用于进行ajax调用,该调用将运行我的php脚本:
jQuery(document).ready(function($){
$(\'.delete-post\').bind(\'click\', function(e){
e.preventDefault();
var post_id;
post_id = $("#post_id").val();
var data = {};
var obj = {data: data};
data[\'post_id\'] = post_id;
alert(\'Are you sure you wish to delete this post?\');
process_delete_post();
function process_delete_post() {
jQuery.ajax({
type: "POST",
url: run_delete_post.ajaxurl,
data: ({
post_id : data[\'post_id\'],
action : \'run_delete_post_script\',
}),
success: function() {
location.href = "";
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert(\'Not connect.\\n Verify Network.\');
} else if (jqXHR.status == 404) {
alert(\'Requested page not found. [404]\');
} else if (jqXHR.status == 500) {
alert(\'Internal Server Error [500].\');
} else if (exception === \'parsererror\') {
alert(\'Requested JSON parse failed.\');
} else if (exception === \'timeout\') {
alert(\'Time out error.\');
} else if (exception === \'abort\') {
alert(\'Ajax request aborted.\');
} else {
alert(\'Uncaught Error.\\n\' + jqXHR.responseText);
}
}
});
}
});
});
在我的功能中。php文件,我设置了ajax调用:
function mytheme_delete_post() {
if ( is_page_template( \'edit-delete-posts.php\' ) ) {
wp_enqueue_script( \'process-delete-post\', get_template_directory_uri().\'/js/process-delete-post.js\', array(\'jquery\'), true);
wp_localize_script( \'process-delete-post\', \'run_delete_post\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
}
add_action(\'template_redirect\', \'mytheme_delete_post\');
$dirName = dirname(__FILE__);
$baseName = basename(realpath($dirName));
require_once ("$dirName/functions_custom.php");
add_action("wp_ajax_run_delete_post_script", "run_delete_post_script");
然后,用实际的php脚本在my functions\\u custom中删除帖子。php文件:
function run_delete_post_script() {
// Test for current user
mytheme_get_current_user();
//Get the data from the submit page and convert to php variables
foreach ($_POST as $field => $value) {
if (isset($_POST[$field])) {
$$field = $value;
}
}
wp_delete_post( $post_id );
}