WP auto comment approve for custom post type

2019-08-26 07:31发布

问题:

I have added the action for auto approve comments for my xyz custom post. But its not working when added the condition if($post_type =='course'). I have tried with also filter. But its not working. How can i solve that?

Action:

global $post_type;
if($post_type =='xyz'){
    function action_pre_comment_approved( $array, $int, $int ) { 

    }; 
add_action( 'pre_comment_approved', 'action_pre_comment_approved', 10, 3 ); 
}

Filter:

global $post_type;
if($post_type =='xyz'){
    function filter_pre_comment_approved( $approved, $commentdata ) { 

        return $approved; 
    }; 
    add_filter( 'pre_comment_approved', 'filter_pre_comment_approved', 10, 2 ); 
}

回答1:

The Wordpress internal function which actually sets comment status to approved is seen nowhere in your code:

wp_set_comment_status( $comment_id, $comment_status ) 

Your code might be firing when it sees comment posted but as there is no function which can modify comment status present, the comment does not get approved. In my opinion, when this function is used, you might need only one from 'action' or 'filter' to modify the comment status. Let us know the result if you try this out.

Visit Page from Wordpress Codex for more details on this function



回答2:

Try this code.

function filter_pre_comment_approved( $approved, $commentdata ) {   
    global $post_type;
    if($post_type =='xyz'){
        return $approved; 
    }else{
        return false;
    }
}
add_filter( 'pre_comment_approved', 'filter_pre_comment_approved', 10, 2 );