1

i need to add a privacy-checkbox to the file comment-template.php. I created the checkbox and a paragraph and it looks fine, so far.

<input type="checkbox" name="privacy" value="privacy-key" class="privacyBox" aria-req="true"><p class="pprivacy">Hiermit akzeptiere ich die <a target="blank" href="http://wp.cloudstarter.de/?page_id=156">Datenschutzbedingungen</a><p>

Now, i want to connect this checkbox with the submit-button, so that a user HAS to accept the privacy to comment on a post. Anyone with a clue how to do that? Or it there a plugin, which delivers this services?

2

You can use the provided filters to do all that:

//add your checkbox after the comment field
add_filter( 'comment_form_field_comment', 'my_comment_form_field_comment' );
function my_comment_form_field_comment( $comment_field ) {
    return $comment_field.'<input type="checkbox" name="privacy" value="privacy-key" class="privacyBox" aria-req="true"><p class="pprivacy">Hiermit akzeptiere ich die <a target="blank" href="http://wp.cloudstarter.de/?page_id=156">Datenschutzbedingungen</a><p>';
}
//javascript validation
add_action('wp_footer','valdate_privacy_comment_javascript');
function valdate_privacy_comment_javascript(){
    if (is_single() && comments_open()){
        wp_enqueue_script('jquery');
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($){
            $("#submit").click(function(e){
                if (!$('.privacyBox').prop('checked')){
                    e.preventDefault();
                    alert('You must agree to our privacy term by checking the box ....');
                    return false;
                }
            })
        });
        </script>
        <?php
    }
}

//no js fallback validation
add_filter( 'preprocess_comment', 'verify_comment_privacy' );
function verify_comment_privacy( $commentdata ) {
    if ( ! isset( $_POST['privacy'] ) )
        wp_die( __( 'Error: You must agree to our privacy term by checking the box ....' ) );

    return $commentdata;
}

//save field as comment meta
add_action( 'comment_post', 'save_comment_privacy' );
function save_comment_privacy( $comment_id ) {
    add_comment_meta( $comment_id, 'privacy', $_POST[ 'privacy' ] );
}
  • Ok, thanks for the fast answer. To understand it right, do i need to put all of the code into the comment-template? and where exactly do i have to add this? btw, i understand now how it should work! – Yannic Hansen Dec 19 '13 at 11:39
  • @Bainternet does that go in functions.php? I want to add a privacy checkbox and a privacy policy link. Is this still valid? I dont want to use javascript validation, only php. – Lorthas Oct 24 '17 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.