删除子帖子和指向父帖子的附件链接

时间:2014-04-30 作者:riksof-zeeshan

我有一个层次结构的帖子,每当我删除子帖子时,它的附件就会链接到已删除帖子的父帖子

我怎样才能阻止这一切?

1 个回复
SO网友:TheDeadMedic

如果不“侦听”负责的数据库查询并使用query 过滤器,由于这一行输入wp_delete_post():

// Point all attachments to this post up one level
$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( \'post_type\' => \'attachment\' ) );
以下内容将覆盖查询并将post父项设置回0 (与继承已删除邮件父项相反):

/**
 * Remove the parent fallback for attachments of children when they are
 * deleted.
 *
 * @link http://wordpress.stackexchange.com/q/142916/1685
 */
class WPSE_142916_Remove_Parent_Fallback {
    public static function init( $post_id ) {
        new self( $post_id );
    }

    public function __construct( $post_id ) {
        $this->post_parent = wp_get_post_parent_id( $post_id );
        $this->post_id = $post_id;

        add_action( \'delete_post\', array( $this, \'un_hook\' ) );
        add_filter( \'query\',       array( $this, \'replace\' ) );
    }

    public function replace( $query ) {
        global $wpdb;

        if ( $query === "UPDATE `$wpdb->posts` SET `post_parent` = $this->post_parent WHERE `post_parent` = $this->post_id AND `post_type` = \'attachment\'" ) {
            $query = str_replace( "`post_parent` = $this->post_parent", \'`post_parent` = 0\', $query );
        }

        return $query;
    }

    public function un_hook() {
        remove_action( \'delete_post\', array( $this, \'un_hook\' ) );
        remove_filter( \'query\',       array( $this, \'replace\' ) );
    }
}

add_action( \'before_delete_post\', array( \'WPSE_142916_Remove_Parent_Fallback\', \'init\' ) );

结束