Delete attachment with post

时间:2014-02-17 作者:4ndro1d

我正在尝试为用户发布删除链接,以便他可以删除自己的条目:

global $post;

    if ( !current_user_can( \'delete_bkroadkill\', $post->ID ) )
        return;

$link = "<a href=\'" . wp_nonce_url( get_bloginfo(\'url\') . "/wp-admin/post.php?action=delete&amp;post=" . $post->ID, \'delete-post_\' . $post->ID) . "\'>".$link."</a>";
echo $before . $link . $after;
我怎样才能用这个删除帖子的附件?

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

这是执行此操作的正确挂钩:

add_action(\'before_delete_post\', \'delete_post_attachments\');
function delete_post_attachments($post_id){
    global $wpdb;
    global $post_type;

    if (!$post_type == \'bkroadkill\')
        return;

    $args = array(
        \'post_type\'         => \'attachment\',
        \'post_status\'       => \'any\',
        \'posts_per_page\'    => -1,
        \'post_parent\'       => $post_id
    );
    $attachments = new WP_Query($args);
    $attachment_ids = array();
    if($attachments->have_posts()) : while($attachments->have_posts()) : $attachments->the_post();
            $attachment_ids[] = get_the_id();
        endwhile;
    endif;
    wp_reset_postdata();

    if(!empty($attachment_ids)) :
        $delete_attachments_query = $wpdb->prepare(\'DELETE FROM %1$s WHERE %1$s.ID IN (%2$s)\', $wpdb->posts, join(\',\', $attachment_ids));
        $wpdb->query($delete_attachments_query);
    endif;
}

结束