Vue.js + AJAX Shortcode

My solution was simpler than I thought….

Since I’m just trying to execute shortcodes in the frontend, I can just localize the script and pass the shortcodes as variables:

functions.php

wp_localize_script( 'BUILD-script', 'sharedData',
  array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'mailchimpForm' => do_shortcode('[mc4wp_form id="100"]'),
        'contactForm' => do_shortcode('[contact-form-7 id="98" title="Contact form 1"]')
    )
);

Basically I’m jus assigning the shortcodes to two variables and make them available in my main js bundle.

build.js

So now I can access those shortcodes, rendered, in my components.

export default {
    name: 'my-component',
    data() {
        return {
            mailchimp: '',
            contact: ''
        };
    },
    mounted() {
        this.mailchimp = sharedData.mailchimpForm;
        this.contact = sharedData.contactForm;
    }
}; 

And rendered by simply using the Vue v-html directive:

<div id="mailchimp" class="chimp--container" v-html="mailchimp"></div>
<div id="contact" class="contact--container" v-html="contact"></div>

Hopefully this will help somebody!

Leave a Comment