Search code examples
wordpressvalidationcontact-form-7

Contact form 7 required one of 2 different fields


I have a image upload field and a URL field in CF7 and how can i make it that a user needs to use one of the 2 fields. So select a image or put a link in the URL field?

I already search a little and i saw some options to do it on normal txt fields but that was not working for me i think because of the upload field.


Solution

  • I think i found the solution with a little help of the code from @Aschi33.

    I made the image (upload field) required and the url field not. So there needs to be alwasy a image selected. But with this code:

    function alter_wpcf7_posted_data( $data ) {
    
        if($_POST['url'] != "") {
            $_FILES['image']['tmp_name'] = "urlprovided";
        }
    
        return $data;
    }
    add_filter("wpcf7_posted_data", "alter_wpcf7_posted_data");
    

    if the URL field is filled in then the required image field is faked to be filled in so then the URL field can be used to submit the form.

    And then with this code:

    function cf7_custom_url_check( $result, $url ) {
        if ($result) {
            $regex='/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/';
            if (!preg_match($regex,$url)) $result=FALSE;      
        }
        return $result;
    }
    add_filter( 'wpcf7_is_url', 'cf7_custom_url_check', 10, 2 );
    

    I check if its a real video link from YouTube and if not the field will give a error.