从前端用jQuery删除帖子图片附件

时间:2015-12-20 作者:Iurie

在我的WP 4.4 216th子主题中,我想从插件创建的前端表单中删除帖子图像附件。为了实现这一点,我遵循this answer, 但是删除链接不会删除任何内容(它们将我链接到页面顶部)。这里怎么了?

UPDATE [已解决]

With the commenters help and after fixing some errors I solved my problem. Thank you! Below is the fixed code.

在插件创建的前端表单中,我获取帖子ID并显示其图像附件以及删除链接:

<!-- Display item thumbnails -->
<?php if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && isset( $_POST[\'postid\'] ) ) {
    $images = get_children( array ( \'post_parent\' => $_POST[\'postid\'], \'post_type\' => \'attachment\', \'post_mime_type\' => \'image\' ));
    if ( empty( $images ) ) {
        // no attachments here
    } else {
        echo \'<label for="item_thumbnails">Post thumbnails</label>\';
        echo \'<div class="item_thumbnails">\';
        foreach ( $images as $attachment_id => $attachment ) {
            echo wp_get_attachment_image( $attachment_id, \'thumbnail\' ) . \'<br>\'; ?>
            <!-- add a \'Delete\' link -->
            <a class="remImage" name="<?php echo $attachment_id; ?>" href="#"><?php _e(\'delete\');?></a>
            <input type="hidden" id="att_remove" name="att_remove[]" value="<?php echo $attachment_id; ?>" />
            <input type="hidden" name="nonce" id="nonce" value="<?php echo wp_create_nonce( \'delete_attachment\' ); ?>" />
        <?php }
        echo \'</div>\';
    }
}?>
在插件的“js”子目录中,我创建了一个名为“delete_attachment”的jQuery脚本。js’:

// this is for jQuery 1.7+
//jQuery(\'.remImage\').on(\'click\', function(event) {

// this is for jQuery 1.4.3+
jQuery(document).delegate(\'.remImage\', \'click\', function(event) {

// this is for jQuery 1.3+ (deprecated)
//jQuery(\'.remImage\').live(\'click\', function(event) {

    event.preventDefault();
    var attID = jQuery(this).attr(\'name\');
    jQuery.ajax({
        type: \'post\',
        url: MyAjax.ajaxurl,
        data: {
            action: \'delete_attachment\',
            attID: jQuery(this).attr(\'name\'),
            _ajax_nonce: jQuery(\'#nonce\').val(),
            post_type: \'attachment\'
        },
        success: function() {
            console.log(\'#file-\'+attID)
            jQuery(\'#file-\'+attID).fadeOut();    
        }
    });
})
我将其放入插件文件中:

function the_plugin_scripts() {
    wp_enqueue_script( \'delete-attachment\', plugins_url( \'js/delete_attachment.js\' , __FILE__ ), array(\'jquery\') );
    wp_localize_script( \'delete-attachment\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'the_plugin_scripts\' );
在同一个插件文件中,我添加了一个处理AJAX请求的函数:

add_action( \'wp_ajax_delete_attachment\', \'delete_attachment\' );
function delete_attachment( $post ) {
    //echo $_POST[\'attID\'];
    $msg = \'Attachment ID [\' . $_POST[\'attID\'] . \'] has been deleted!\';
    if( wp_delete_attachment( $_POST[\'attID\'], true )) {
        echo $msg;
    }
    die();
}

1 个回复
最合适的回答,由SO网友:jgraup 整理而成

现在您需要处理AJAX 在PHP中调用。

add_action( \'wp_ajax_delete_attachment\', \'delete_attachment\' );
function delete_attachment( $post ) {
//echo $_POST[\'att_ID\'];
$msg = \'Attachment ID [\' . $_POST[\'att_ID\'] . \'] has been deleted!\';
if( wp_delete_attachment( $_POST[\'att_ID\'], true )) {
    echo $msg;
}
die();
}
至于你的活动,只需将其添加到单击功能中,那么里面的所有内容都会知道你在说什么。

jQuery(\'.remImage\').on(\'click\', function(event) {
测试AJAX

将其复制并粘贴到函数中。它将自动运行,并应在警报和控制台中输出来自AJAX的响应。

<小时>

function ajax_delete_attachment_handler() {

    $data = json_encode(array(\'message\' => \'THIS IS AJAX WORKING\', \'$_POST\' => $_POST));
    wp_send_json_success($data);
}

$action_name = \'delete_attachment\';
add_action("wp_ajax_nopriv_$action_name", \'ajax_delete_attachment_handler\');
add_action("wp_ajax_$action_name", \'ajax_delete_attachment_handler\');
add_action(\'wp_footer\', function() {
    ?>
    <script>
        jQuery.ajax({
            type: \'POST\',
            cache: false,
            dataType: \'json\',
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: \'delete_attachment\',
                ID: \'some ID here\',
                \'foo\': \'bar\'
            },
            success: function (response) {

                // we encoded the data, so let\'s decode it first
                var json = JSON.parse(response.data);

                console.log(\'response: \', response);
                console.log(\'json parsed: \', json);

                alert(response.data);
            },
            fail: function (response) {
                console.log(\'FAILED: \' + response);
            }
        });
    </script>
    <?php
});