简体   繁体   English

HTML输出中的WordPress简码

[英]WordPress shortcode in HTML output

I'm just wondering is it possible to output a wordpress shortcode inside html output in my javascript page? 我只是想知道是否可以在我的JavaScript页面的html输出中输出wordpress简码?

You see I have a javascript file and inside it is below: 您会看到我有一个javascript文件,其内容如下:

$(document).ready(function () {
    $("#bannav li a").on("click", function (e) {
        e.preventDefault();
        var hrefval = $(this).attr("href");
        if (hrefval == "#enquire") {
          var distance = $('#banner').css('right');
          $('.banner-rt-content1').html('
            <div style="padding:20px;">
            [contact-form-7 id="102" title="Make an Enquiry"]
            </div>
          ');
          if (distance == "auto" || distance == "0px") {
            $(this).addClass("open");
            openSidepage();
          }
        }

The thing is I want to output my Contact Form 7 form within this JS page using their WordPress shortcode [contact-form-7 id="102" title="Make an Enquiry"] . 问题是我想使用其WordPress短代码[contact-form-7 id="102" title="Make an Enquiry"]在此JS页面中输出我的Contact Form 7表单。 Is that even possible? 那有可能吗?

Shortcodes in Wordpress are processed in PHP before the page loads. 在页面加载之前,将使用PHP处理Wordpress中的简码。 Unfortunately there isn't a super easy way to process them directly in your javascript. 不幸的是,没有一种简单的方法可以直接在您的javascript中直接处理它们。 You need to either make an AJAX handler to get the output of the processed shortcode, or have PHP write the javascript for you. 您需要制作一个AJAX处理程序以获取处理后的短代码的输出,或者让PHP为您编写JavaScript。 AJAX in Wordpress is slightly more difficult than the second option so I will explain that one instead. Wordpress中的AJAX比第二个选项稍微困难一点,因此我将解释一个。

You can localize the output of your shortcode and then reference it in your javascript. 您可以本地化短代码的输出,然后在javascript中引用它。 Since most wordpress themes use jQuery I will localize the script to that. 由于大多数wordpress主题都使用jQuery,因此我将脚本本地化为jQuery。 Add this to your functions file: 将此添加到您的功能文件:

$translation = do_shortcode('[contact-form-7 id="102" title="Make an Enquiry"]');

wp_localize_script( 'jquery', 'contact_form', array( 'html' => $translation) );

Then in your javascript do this: 然后在您的JavaScript中执行以下操作:

$('.banner-rt-content1').html('<div style="padding:20px;">'+contact_form.html+'</div>');

That should get the content you need into the page. 那应该把您需要的内容带入页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM