wordpresscommentscustom-fieldsmeta-key

Add custom field/checkbox to wordpress comments


I want to display selected comments using get_comments and I see that there is meta_query arguments for that ..

But I don't understand what will be the meta key.

Is there a way I could add a featured checked box(meta key) in comments in wordpress backend ..

Please guide me in the right direction


Solution

  • Yes! you can add featured checkbox for comment at admin panel. Put below code in your theme's functions.php, It will add featured checkbox at admin panel. The checkbox will appear when you edit any comment.

    add_action( 'add_meta_boxes_comment', 'display_comment_add_meta_box' );
    function display_comment_add_meta_box()
    {
        add_meta_box( 'featured', __( 'Featured' ), 'display_meta_box_field', 'comment', 'normal', 'high' );
    }
    function display_meta_box_field( $comment )
    {
        wp_nonce_field( 'featured_update', 'featured_update', false );
        $featured = get_comment_meta( $comment->comment_ID, 'featured', true );
        $checked="";
        if($featured)
            $checked = " checked='checked'";
        ?>
        <p>
            <label for="featured"><?php _e( 'Featured' ); ?></label>
            <input type="checkbox" name="featured" value="1" class="widefat" <?php echo $checked; ?> />
        </p>
        <?php
    }
    
    add_action( 'edit_comment', 'comment_edit_function' );
    function comment_edit_function( $comment_id )
    {
        if ( ( isset( $_POST['featured'] ) ) && ( $_POST['featured'] != '') )
            $featured = wp_filter_nohtml_kses($_POST['featured']);
    
        update_comment_meta( $comment_id, 'featured', $featured );  
    }