• Hi guys,

    I saw this related topic and found an alternative approach to enable Contact Form 7 within a WP Post Modal.

    The actual issue:
    When submitting the form within the modal, I don’t get an immerdiate response but it always redirects to the actual page without a response. Usually, the form would not open a new page but give a success or error response via Javascript (collecting the result via AJAX). This behaviour is just not active since WPCF7 would only once check on the current page for forms and initialize them. Since the form is loaded later via the post modal, the Javascript of WPCF7 logic is not applied on this new form.

    Solution:
    1. Enqueue a new script (e.g. via your own wordpress theme)

    
    wp_enqueue_script('popup-wpcf7', get_stylesheet_directory_uri() . '/assets/js/popup-wpcf7.js', array('jquery'), $version, true);
    

    2. Create the new script file “popup-wpcf7.js” in your theme (& eventually update the path above accordingly):

    
    jQuery(function ($) {
      var _oldHTML = $.fn.html;
    
      $.fn.html = function (content) {
        const returnValue = _oldHTML.apply(this, [content]);
        if (content) {
          $(this).trigger("afterChangeElementHtml", [content]);
        }
        return returnValue;
      };
    
      function initializePopupWPCF7() {
        $("#modal-content div.wpcf7 > form").each(function () {
          // Copied from contact-form-7/includes/js/scripts.js:29
          var $form = $(this);
          wpcf7.initForm($form);
    
          if (wpcf7.cached) {
            wpcf7.refill($form);
          }
        });
      }
    
      $(document).bind("afterChangeElementHtml", function (event, content) {
        const isModal = $(event.target).attr("id") === "modal-content";
        if (isModal && $(event.target).has(".wpcf7").length) {
          initializePopupWPCF7();
        }
      });
    });
    

    This listens on jQueries html() method which is used by WP Post Modal to insert the loaded content. We listen on this event by customizing $.fn.html. With some safety checks, we make sure that this is called by WP Post Modal and inserts a new WPCF7 form. Then, the initialization code by WPCF7 is triggered again to enable its expected functionalities.

    My approach is not very sustainable since I needed to copy the initialization code from WPCF7 but its’ only three lines ??

    I wanted to share this with you (& anyone looking for a solution to this problem). I am happy to hear about other more stable solutions.

    Feature Request:
    It’s probably a good idea to add a section “Compatibility with other Plugins” and mention known problems and workarounds.

    Greetings,
    Thomas

  • The topic ‘Compatibility with Contact Form 7’ is closed to new replies.