简体   繁体   中英

WordPress shortcode in HTML output

I'm just wondering is it possible to output a wordpress shortcode inside html output in my javascript page?

You see I have a javascript file and inside it is below:

$(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"] . Is that even possible?

Shortcodes in Wordpress are processed in PHP before the page loads. Unfortunately there isn't a super easy way to process them directly in your 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 in Wordpress is slightly more difficult than the second option so I will explain that one instead.

You can localize the output of your shortcode and then reference it in your javascript. Since most wordpress themes use jQuery I will localize the script to that. 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:

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

That should get the content you need into the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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