contact form 7 in wordpress how to include javascript src in body - Stack Overflow

I'm using wordpress, and contact form 7 plugin.What's i'm trying to acplish is that som

I'm using wordpress, and contact form 7 plugin. What's i'm trying to acplish is that some of the drop down menus are populated with custom javascript, I know that you can include it with another plugin "Scripts and Stuff" for example. but I wanted to put it in a seperate file and include the file in the body tags of the contact form with script src=".js" (actual form created with the plugin)

EDIT: i donot want to add it to a footer.php of the theme, I want the script src to be on a Single page only. not the entire theme

I'm using wordpress, and contact form 7 plugin. What's i'm trying to acplish is that some of the drop down menus are populated with custom javascript, I know that you can include it with another plugin "Scripts and Stuff" for example. but I wanted to put it in a seperate file and include the file in the body tags of the contact form with script src="http://example/myscript.js" (actual form created with the plugin)

EDIT: i donot want to add it to a footer.php of the theme, I want the script src to be on a Single page only. not the entire theme

Share Improve this question edited Feb 6, 2017 at 23:53 sim555 asked Feb 6, 2017 at 23:37 sim555sim555 131 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

sure, that's quite straight forward. There are 2 ways to achieve this,

  1. you can either insert a <script>with your js code</script> at the bottom of your form inside the cf7 form editor, this way the script loads only when the form is printed on the page. However, make sure you don't add any new lines spaces in your js code else cf7 plugin will insert empty <p></p> elements and this will break your code at execution. Alternatively,
  2. if you are running WP4.7 you can now use the do_shortcode_tag which has been introduced with this release to actually enqueue your script on the same page as which the form is being printed, but remember to register that script earlier on first,

    add_filter('wp_enqueue_scripts', 'register_my_script');
    function register_my_script(){
      wp_register_script( 'my-script', get_stylesheet_directory_uri() . 'js/my-script.js', array( 'jquery' ), "1.0" , false );
    }
    add_filter('do_shortcode_tag', 'enqueue_my_script',10,3);
    function enqueue_my_script($output, $tag, $attr){
      if('contact-form-7' != $tag){ 
        return $output; //make sure we filter cf7 shortcodes
      }
      if(isset($attr['id']) && '4' == $attr['id']){
        wp_enqueue_script('my-script'); //enqueue if it is form id=4
      }
      return $output;
    }
    

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745261259a4619221.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信