如何在删除帖子时防止删除评论

时间:2012-12-04 作者:jochem

正如标题所说:当我删除帖子时,如何防止Wordpress删除帖子评论?

我试图做到的是,我想将来自不同帖子的所有评论合并到通过帖子标题或帖子中预定义的元键相互关联的帖子中。有时我会删除一篇绝对删除的帖子,但我仍然希望这些评论在未删除的帖子中显示出来。

我已经为我的函数编写了一些注释聚合代码。php。(仍然需要对查询部分进行一些调整,以获得基于评论元而不是评论帖子id的结果)。

function multiple_comment_post_id_query_filter( $query )
{
    //todo:
    //get postid\'s from comments where a certain meta value is set. Database table wp_commentmeta
    //the meta value is extracted from the post meta value with the same id
    //when someone adds a comment, the comment meta will be included
    //put the captured post id\'s into an array with variable $post_ids 
    $post_ids = array ( 1, 2, 3, 4 );
    if ( FALSE === strpos( $query, \'comment_post_ID = \' ) )
    {
        return $query; // not the query we want to filter
    }

    remove_filter( \'query\', \'multiple_comment_post_id_query_filter\' );

    $replacement = \'comment_post_ID IN(\' . implode( \',\', $post_ids ) . \')\';
    return preg_replace( \'~comment_post_ID = \\d+~\', $replacement, $query );
}
add_filter( \'query\', \'multiple_comment_post_id_query_filter\' );
我宁愿不编辑核心文件,以防我必须升级(如果没有其他可能的方法,我会这样做…)

1 个回复
SO网友:fuxia

防止注释删除挂钩进入before_delete_post, 并过滤query 以便删除例程无法找到并删除相关注释。

PHP 5.3要求:

add_action( \'before_delete_post\', function( $post_id ) {
    add_filter( \'query\', function( $query ) use ( $post_id ) {
        $find = \'WHERE comment_parent = \';
        FALSE !== strpos( $query, $find . $post_id )
            and $query = str_replace( $find . $post_id, $find . \'-1\', $query );

        return $query;
    });
});
这是一个吵闹的老派版本:

add_action(
    \'before_delete_post\',
    array ( \'T5_Prevent_Comment_Deletion\', \'start\' )
);

class T5_Prevent_Comment_Deletion
{
    protected static $post_id = 0;

    public static function start( $post_id )
    {
        self::$post_id = $post_id;
        add_filter( \'query\', array ( __CLASS__, \'hide_comments\' ) );
    }

    public function hide_comments( $query )
    {
        $find = \'WHERE comment_parent = \' . self::$post_id;

        if ( FALSE !== strpos( $query, $find ) )
        {
            $query = str_replace( $find, \'WHERE comment_parent = -1\', $query );
            remove_filter( \'query\', array ( __CLASS__, \'hide_comments\' ) );
        }

        return $query;
    }
}

结束