delete post also attachments

时间:2011-11-23 作者:boranb

我正在尝试删除包含所有附件的帖子。这就是我现在想到的函数;

function remove_post(){
            if(isset($_POST[\'post_id\']) && is_numeric($_POST[\'post_id\'])){
                $post = get_post($_POST[\'post_id\']);
                if(get_current_user_id() == $post->post_author){ echo \'ee\';
                    wp_delete_post($_POST[\'post_id\']);
                }
            }  

            exit;
        }
这会删除帖子,但不会删除指向该帖子的附件链接,也不难删除,帖子仍保留在垃圾桶中。那你觉得呢?谢谢

2 个回复
最合适的回答,由SO网友:Andres Yanez 整理而成

也许这样行得通

function remove_post() {

            if(isset($_POST[\'post_id\']) && is_numeric($_POST[\'post_id\'])) {

                $post = get_post($_POST[\'post_id\']);

                if(get_current_user_id() == $post->post_author) { 


                     $args = array(
                             \'post_parent\' => $_POST[\'post_id\']
                 );

                 $post_attachments = get_children($args);

                     if($post_attachments) {

                            foreach ($post_attachments as $attachment) {

                                      wp_delete_attachment($attachment->ID, true);

                            }

                     }

                          wp_delete_post($_POST[\'post_id\'], true);

                }

            }  

            exit;
}
添加的代码

function get_attachment_id_from_src ($image_src) {
  global $wpdb;

  $query = "SELECT ID FROM {$wpdb->posts} WHERE guid=\'$image_src\'";
  $id = $wpdb->get_var($query);

  return $id;

}

if(!empty($_POST[\'avatar_id\'])  && $_POST[\'avatar_id\'] != get_user_meta($current_user->id, \'custom_avatar\', true) && empty( $_POST[\'remove_avatar\'])) {

        update_user_meta($current_user->id, \'custom_avatar\', esc_attr( $_POST[\'avatar_id\']));

    } elseif(!empty( $_POST[\'remove_avatar\']) && $_POST[\'remove_avatar\'] == 1) {

                $avatar_url = get_user_meta($current_user->id, \'custom_avatar\', true);

                $attachment_delete = get_attachment_id_from_src($avatar_url);

                wp_delete_attachment($attachment_delete, true);

        update_user_meta( $current_user->id, \'custom_avatar\', \'-1\');

    }

SO网友:keatch

有关正确使用wp_delete_post, 使用

wp_delete_post( $_POST[\'id\'], true );
绕过垃圾桶

结束

相关推荐

Adding a filter to my posts

大家好,我想在我帖子的内容末尾添加一个链接。我目前在我的功能中有此功能。php文件:function ifcj_comment_link() { global $post; return \' <a href=\"\'. get_post_meta($post->ID, \'Israel In The News Audio Link\', true) . \'\">\' . __( \'<div id=\"audio-player\">Testing</