Using Vue in WordPress
Tags: vue, wordpress, javascript, web
Published: 2019-04-03 17:02:32

---
title: Using Vue in WordPress
published: true
description: How to add Vue.js to WordPress and use it in a plugin or theme.
tags: #vue, #wordpress, #javascript, #web
---

{% raw %}
<p>Like peanut butter and jam sometimes two good things are even better together. </p>



<p>In this tutorial I'll show you how to use Vue in a WordPress site.   The tutorial is meant for those who have coded in WordPress and Vue or is interested in either one.  Knowledge in PHP, WordPress, Javascript, Vue will help.  </p>



<h2>Vue Programmers: Why WordPress?  </h2>



<p>Statistically, WordPress runs about a third of the world's websites.  If you've created something in Vue you'd like to share,  WordPress is a good platform to make it available on.  </p>



<p>You can customize your own site, or share your code on WordPress' plugin repository.</p>



<h2>WordPress Programmers: Why Vue?  </h2>



<p>The short answer is, Vue is known for its simplicity and robustness making it a solid choice for development. If you're adding functionality to your site, it makes a good tool to get up and running with. It's in JavaScript, so it's familiar to most developers.</p>



<p>WordPress uses React,  can I even use Vue?<br>Of course! Although some features in WordPress may be in React,  you are not limited to it.</p>



<p>WordPress is open source, do what makes you happy.</p>



<h2>Tutorial Overview</h2>



<p>We'll make a short code that displays something generated in Vue.  We'll be using a simple example because this is more about how to put Vue and WordPress together rather than what they do.</p>



<p> The approach is: </p>



<ol><li><strong>Create a plugin</strong> in WordPress to use the code </li><li><strong>Create a shortcode</strong> in the plugin</li><li><strong>Create your Vue</strong> code</li><li><strong>Load Vue</strong>,  then <strong>your code </strong>file.  </li><li>Make sure your <strong>.js file is loaded after the dom</strong> is drawn. </li></ol>



<p>That's basically it.  Let's get into the details. </p>



<h2>WordPress:  The Plugin. </h2>



<p>Plugins are both simple and robust, they allow you to add functionality to your site.  This plugin will be a simple 'hello world' type. We'll call it '<strong>wp-vue-tutorial</strong>', so let's begin:</p>



<h3>1) Create a new folder in your WordPress plugin directory.</h3>



<p>This is where the files will be kept, it should be the name of the plugin.  For this tutorial let's use:  <br><strong>/wp-content/plugins/wp-vue-tutorial</strong></p>



<p>We need a 'master file', so let's make that.</p>



<h3>2) In the directory, create a master file with the plugin name.</h3>



<p>This file called '<strong>wp-vue-tutorial.php</strong>' so it should look like:<br><strong>/wp-content/plugins/wp-vue-tutorial/wp-vue-tutorial.php</strong></p>



<p>Yes, the <strong>plugin name, folder name and master file name are all the same </strong>so WordPress knows where to find it.</p>



<p>Once WordPress opens it up, it needs some more info on what this thing is.  That's included in the Header.  We're keeping it simple, so in <strong>wp-vue-tutorial.php</strong>, add the following code:</p>



<pre class="wp-block-code"><code>&lt;?php
/**
 * Plugin Name: WordPress Vue Tutorial
 * Description: A demo on how to use Vue in WordPress.
 */
?&gt;</code></pre>



<p>More info:  <a href="https://developer.wordpress.org/plugins/" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">https://developer.wordpress.org/plugins/</a></p>



<p>If you go to your WordPress Dashboard, you'll see your plugin.<br><strong>Dashboard </strong>-&gt; <strong>Plugins</strong><br>It should appear in the list. </p>



<h3>3) Activate your plugin.</h3>



<p><strong>Click Activate</strong> on your plugin.</p>



<p>Now it's loaded,  but not much happens because there's no code to run.  So, let's create a shortcode.</p>



<p>A shortcode tells WordPress to insert the content generated by your PHP code into the content of the page or post. <br>Ex.  The user enters something like <em>[myshortcode]</em> and when the page is displayed, it shows '<em>This is content from my shortcode.</em>'</p>



<p class="has-small-font-size">Note:  WordPress' current text editor (Gutenberg) allows you to put in blocks of content in.  A shortcode will still work with that, in fact there is a block specifically for short codes.  We're using shortcodes in this tutorial because it's a standard that works.</p>



<p> For more info: <a rel="noreferrer noopener" target="_blank" href="https://codex.wordpress.org/Shortcode_API">https://codex.wordpress.org/Shortcode_API</a></p>



<h3>4) Create a shortcode in your Plugin.</h3>



<p>Add the following code to your plugin file (<strong>wp-vue-tutorial.php</strong>):</p>



<pre class="wp-block-code"><code> //Add shortscode
 function func_wp_vue(){
   return "Hello Shortcode";
}
add_shortcode( 'wpvue', 'func_wp_vue' );</code></pre>



<p>Breaking it down:<br>The function func_wp_vue() returns the text Hello Shortcode.</p>



<table class="wp-block-table"><tbody><tr><td> add_shortcode(  </td><td><em>Make this shortcode available.  </em></td></tr><tr><td> 'wpvue', </td><td><em>The code the user uses in the content</em><br><em>[ 'wpvue'].</em></td></tr><tr><td>  'func_wp_vue'  </td><td><em>The function returning the string to display.  </em></td></tr><tr><td> ); </td><td><em>End of shortcode.</em></td></tr></tbody></table>



<p>Your file should look like:</p>



<pre class="wp-block-code"><code>&lt;?php
/**
 * Plugin Name: WordPress Vue Tutorial
 * Description: A demo on how to use Vue in WordPress.
 */

//Add shortscode
 function func_wp_vue(){
 return "Hello Shortcode";
}
add_shortcode( 'wpvue', 'func_wp_vue' );
?&gt;</code></pre>



<p>Test it.<br><strong>Edit</strong>,  or <strong>add a new</strong> WordPress <strong>page</strong>.  In the <strong>content </strong>area,  type in <strong>[wpvue]</strong>.<br><strong>Publish</strong> the page and have a look at it. You should see <em>Hello Shortcode</em>.</p>



<p>The short code can return more than a word, we can put in an element in the too.</p>



<p>Let's change the code to:</p>



<pre class="wp-block-code"><code>//Add shortscode
function func_wp_vue(){
  $str= "&lt;div id='divWpVue'&gt;"
    ."Message from Vue: "
    ."&lt;/div&gt;";
  return $str;
} // end function</code></pre>



<p> Test it again.</p>



<h2>Set Up Vue</h2>



<p>To use Vue,  you need three things:</p>



<ol><li> <strong>Vue js files</strong> need to be loaded on the page so you can use the framework.  </li><li> You need an <strong>element </strong>on your page Vue can work in. Usually a div.</li><li> You need your <strong>Vue code in a .js</strong> file to do its work in the element.  </li></ol>



<h3>Load Vue.js</h3>



<p>Let's start with adding Vue. You can add Vue through a link to a CDN. There's 2 versions, one for development with debugging options and one for production that is faster and leaner.<br>We'll use the development one: <strong>https://cdn.jsdelivr.net/npm/vue/dist/vue.js</strong></p>



<p>We need to load this into WordPress, which can be done through the magic of '<strong>wp enqueue scripts</strong>' and '<strong>wp_register_script</strong>'.<br>This hook automatically load the script into WordPress' head when needed.</p>



<p>It looks like:</p>



<pre class="wp-block-code"><code>function func_load_vuescripts() {
 wp_register_script( 'wpvue_vuejs', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
}
add_action('wp_enqueue_scripts', 'func_load_vuescripts');</code></pre>



<p>Break down:</p>



<table class="wp-block-table"><tbody><tr><td> function func_load_vuescripts() {  </td><td><em> Define the function .</em></td></tr><tr><td> wp_register_script(   </td><td> <em>Tell WP this script exists </em><br><em>(we'll load it later)</em> .</td></tr><tr><td>  'wpvue_vuejs',  </td><td><em>This is the WordPress reference to the script. </em></td></tr><tr><td> ''https://cdn.jsdelivr.net/npm/vue/dist/vue.js'', </td><td><em>Actual script file.  </em></td></tr><tr><td> );  </td><td> <em>Close the wp_register_script. </em></td></tr><tr><td> }  </td><td><em>Close the function.  </em></td></tr><tr><td>add_action(  </td><td><em>WordPress, do this.</em></td></tr><tr><td> 'wp_enqueue_scripts',  </td><td><em>Hook into 'wp_enqueue_scripts'.</em></td></tr><tr><td> 'func_load_vuescripts' </td><td><em>Do this function for 'wp_enqueue_scripts' .</em></td></tr><tr><td> );  </td><td> <em>End action .</em></td></tr></tbody></table>



<p>For more info: </p>



<ul><li>Register Scripts: <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://developer.wordpress.org/reference/functions/wp_register_script/ " target="_blank">https://developer.wordpress.org/reference/functions/wp_register_script/ </a></li><li>Enque Scripts:   <a rel="noreferrer noopener" aria-label="https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts  (opens in a new tab)" href="https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts " target="_blank">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts </a></li></ul>



<p>We'll <strong>add the code to your plugin file</strong>, above the shortcode.<br>It should look like this: </p>



<pre class="wp-block-code"><code>&lt;?php
/**
 * Plugin Name: WordPress Vue Tutorial
 * Description: A demo on how to use Vue in WordPress.
 */

//Register Scripts to use 
function func_load_vuescripts() {
 wp_register_script( 'wpvue_vuejs', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
}
add_action('wp_enqueue_scripts', 'func_load_vuescripts');

//Add shortscode
function func_wp_vue(){
  //Build String
  $str= "&lt;div id='divWpVue'&gt;"
  ."Vue code here: "
  ."&lt;/div&gt;";

  //Return
  return $str;
} // end function

//Add shortcode to WordPress
add_shortcode( 'wpvue', 'func_wp_vue' );
?&gt;</code></pre>



<p>Right now, we told WordPress about Vue.js, but we haven't loaded it.  You load it in the shortcode function so it fires when the shortcode is running.  Makes sense?</p>



<p>Include the following in your shortcode function:</p>



<pre class="wp-block-code"><code>//Add Vue.js
  wp_enqueue_script('wpvue_vuejs');</code></pre>



<p>Breakdown:</p>



<table class="wp-block-table"><tbody><tr><td> wp_enqueue_script(  </td><td><em> WordPress, load this script </em></td></tr><tr><td> 'wpvue_vuejs' </td><td><em> It's called 'wpvue_vuejs' defined when we registered the script.</em></td></tr><tr><td> );  </td><td><em>End enqueue script</em></td></tr></tbody></table>



<p>It should look like:</p>



<pre class="wp-block-code"><code>function func_wp_vue(){
  //Add Vue.js
  wp_enqueue_script('wpvue_vuejs');
  
  //Build String
  $str= "&lt;div id='divWpVue'&gt;"
  ."Vue code here: "
  ."&lt;/div&gt;";

  //Return
  return $str;
} // end function</code></pre>



<p>Now if you run it, not much has changed, but if you were to look in the <strong>source code </strong>of the page you'd find :</p>



<p> <strong>&lt;script type='text/javascript' src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js?ver=5.1.1'&gt;&lt;/script&gt;</strong> <br></p>



<p>Vue is now loaded, we can use the div generated in the shortcode ('<em>divWpVue</em>'), all we need is some Vue code to run in that div.</p>



<h3>Create Your Code File for Vue</h3>



<p>Make a new file: <strong>vuecode.js</strong> your plugin directory:  <br><strong>wp-content/plugins/wp-vue-tutorial</strong> </p>



<p>You should have 2 files in there:  </p>



<ul><li> wp-vue-tutorial.php </li><li> vuecode.js </li></ul>



<p>More Info:<br><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://vuejs.org/v2/guide/" target="_blank">https://vuejs.org/v2/guide/</a></p>



<p>This is a really simple demo, so include the following code:</p>



<pre class="wp-block-code"><code>var app = new Vue({
  el: '#divWpVue',
  data: {
    message: 'Hello Vue!'
  }
})</code></pre>



<p>Breakdown:</p>



<table class="wp-block-table"><tbody><tr><td>var app = new Vue({</td><td><em>We're creating a var called 'app' that is actually a Vue instance.</em></td></tr><tr><td>el: '#divWpVue',</td><td><em>This app runs in the element 'divWpVue'.</em></td></tr><tr><td>data: {</td><td><em>This app has data with it.</em></td></tr><tr><td>message: 'Hello Vue!'</td><td><em>One piece of data is called 'message' and has the value  'Hello Vue!' </em></td></tr><tr><td>}<br> })</td><td><em>Close the data section<br>Close the app section</em></td></tr></tbody></table>



<p>For more info on Vue: </p>



<ul><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://vuejs.org/v2/guide/index.html" target="_blank">https://vuejs.org/v2/guide/index.html</a> </li><li><a href="https://vuejs.org/v2/guide/#Declarative-Rendering" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">https://vuejs.org/v2/guide/#Declarative-Rendering</a> </li></ul>



<p>In order to display the message, you need to include the data message in the div.  Change your shortcode function  (<strong>func_wp_vue</strong>) to include <strong>{{message}}</strong>.  </p>



<p>The double curly brackets is a way of including Vue stuff in your HTML file. If you add <em>{{message}}</em> inside the element you've assigned to your Vue instance, it will magically appear. This is the short non-technical answer of course.</p>



<p><strong>Important!</strong>  If you check your file, and everything is working, you will see <em>'Hello Vue!'</em> where <em>{{message}}</em> was placed.  If you see <em>{{message}}</em>, something's not working.</p>



<p>Let's <strong>add the </strong><em><strong>{{message}}</strong></em><strong> to the shortcode</strong>.  </p>



<pre class="wp-block-code"><code>function func_wp_vue(){
  //Add Vue.js
  wp_enqueue_script('wpvue_vuejs');
  
  //Build String
  $str= "&lt;div id='divWpVue'&gt;"
  ."Message from Vue: {{ message }}"
  ."&lt;/div&gt;";

  //Return
  return $str;
} // end function</code></pre>



<p>If you test it now, it won't work, <em>{{message}}</em> will display, not <em>'Hello Vue!' </em></p>



<p>Why? Because we haven't loaded your <em>vuecode.js</em><strong> </strong>file yet. We can load it the same was as the Vue CDN file, right?</p>



<p>Hmm... not exactly.   You're on the right track, but there's a couple of Gotcha's to watch out for.  Let's walk through it.</p>



<p>To register  vuecode.js, you would expect something like the following would work:</p>



<pre class="wp-block-code"><code> wp_register_script('my_vuecode', 'vuecode.js')</code></pre>



<p>No, it won't because WordPress can't find  <em>vuecode.js.</em>  </p>



<p class="has-medium-font-size"><strong>Gotcha:  Your file isn't loading</strong></p>



<p>Remember the shortcode is displayed on a page with a different path than the plugin. It's a kind of logistical hall of mirrors, nothing is where it appears.</p>



<p>To fix it, you need to be more precise about where the file is located. That's handled by adding a WordPress function that returns the path of the plugin file you're using. <strong>plugin_dir_url</strong> will do the trick.</p>



<pre class="wp-block-code"><code>wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ).'vuecode.js') </code></pre>



<p>More info on plugin urls:   <a href="https://codex.wordpress.org/Function_Reference/plugins_url" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">https://codex.wordpress.org/Function_Reference/plugins_url</a> </p>



<p class="has-medium-font-size"><strong>Gotcha:  Vue.js needs to load first</strong></p>



<p>Your vuecode.js runs on Vue, so make sure those files are loaded <em>before</em> you start running your Vue code.</p>



<p>To ensure that, tell WordPress it <em>depends</em> on Vuejs by <strong>adding the dependency</strong> to the register_script function.  Use the handle from the Vue.js script register.</p>



<pre class="wp-block-code"><code>wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ).'vuecode.js', 'wpvue_vuejs' );</code></pre>



<p class="has-medium-font-size"><strong>GOTCHA:  Your file with Vue code has to come AFTER the DOM loads</strong></p>



<p>Why? It loads scripts in the <em>head</em>, but your vuecode.js controlling a div in the <em>body </em>and it hasn't been loaded yet. It can't find it and throws an error.</p>



<p>So, <strong>load Vue.js first</strong>, then the body with the DOM, then the controlling script ( vuecode.js ).  You can do that through the <strong>register script</strong> by <strong>adding a 'true' value to the parameters</strong>.  '<em>true</em>' tells WordPress to load the script in the footer.</p>



<p>It should look like this:</p>



<pre class="wp-block-code"><code>wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ).'vuecode.js', 'wpvue_vuejs', true );</code></pre>



<p>Breaking it down:</p>



<table class="wp-block-table is-style-regular"><tbody><tr><td>wp_register_script(</td><td><em>WordPress, register this script.</em></td></tr><tr><td>'my_vuecode',</td><td><em>Its handle (reference) .</em></td></tr><tr><td>plugin_dir_url( __<strong>FILE</strong> __).'vuecode.js',</td><td><em>The file is located in the same directory as this plugin.  This is the link to it.</em></td></tr><tr><td>'wpvue_vuejs',</td><td><em>Make sure this is loaded first.  It's a reference to another <strong>registered </strong>script.</em></td></tr><tr><td>true </td><td><em>Load the script in the footer.</em></td></tr><tr><td>);</td><td><em>Close the function.</em></td></tr></tbody></table>



<p>Your function to load the scripts should look like:</p>



<pre class="wp-block-code"><code>//Register scripts to use
function func_load_vuescripts() {
	wp_register_script('wpvue_vuejs', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
	wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ).'vuecode.js', 'wpvue_vuejs', true );
}
add_action('wp_enqueue_scripts', 'func_load_vuescripts');</code></pre>



<p>More Info on Registering Scripts:</p>



<ul><li>Register Script:  <br><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://developer.wordpress.org/reference/functions/wp_register_script/" target="_blank">https://developer.wordpress.org/reference/functions/wp_register_script/</a> </li><li>Plugin URL:  <br><a href="https://codex.wordpress.org/Function_Reference/plugin_dir_url" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">https://codex.wordpress.org/Function_Reference/plugin_dir_url</a> </li></ul>



<p>That should do it.  But, you still won't see anything, why not?  <br>After all that, you've only registered the script.  WordPress knows all about it, but you haven't told it to fire it.</p>



<p class="has-medium-font-size"><strong>Gotcha:  Don't forget to enqueue /load  the script</strong></p>



<p>Ok, this one is just like enqueing the Vue.js script.   Add the following to the shortcode function -- '<strong>func_wp_vue</strong>'.</p>



<pre class="wp-block-code"><code>wp_enqueue_script('my_vuecode');</code></pre>



<p> '<strong>func_wp_vue </strong>' should look like:</p>



<pre class="wp-block-code"><code>//Return string for shortcode
function func_wp_vue(){
  //Add Vue.js
  wp_enqueue_script('wpvue_vuejs');
  //Add my code to it
  wp_enqueue_script('my_vuecode');

  //Build String
  $str= "&lt;div id='divWpVue'&gt;"
  	."Message from Vue: {{ message }}"
  	."&lt;/div&gt;";

  //Return to display
  return $str;
} // end function

//Add shortcode to WordPress
add_shortcode( 'wpvue', 'func_wp_vue' );</code></pre>



<h2>Putting It All Together:</h2>



<p>You should have your plugin called 'wp-vue-tutorial'.  In the plugin directory, there should be 2 files:</p>



<ul><li><strong>vuecode.js</strong> (that has the Vue code in it)</li><li><strong>wp-vue-tutorial.php</strong> (with the WordPress code)</li></ul>



<h3> <strong>vuecode.js</strong></h3>



<p> Your Javascript file that runs off of Vue.js should look like the following:</p>



<pre class="wp-block-code"><code>var app = new Vue({
  el: '#divWpVue',
  data: {
    message: 'Hello Vue!'
  }
})</code></pre>



<h3><strong>wp-vue-tutorial.php</strong> </h3>



<p>Your WordPress file that defines the plugin and has the shortcode code in it should look like:</p>



<pre class="wp-block-code"><code>&lt;?php
/**
 * Plugin Name: WordPress Vue Tutorial
 * Description: A demo on how to use Vue in WordPress.
 */

//Register scripts to use
function func_load_vuescripts() {
	wp_register_script('wpvue_vuejs', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
	wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ).'vuecode.js', 'wpvue_vuejs', true );
}
//Tell WordPress to register the scripts 
add_action('wp_enqueue_scripts', 'func_load_vuescripts');


//Return string for shortcode
function func_wp_vue(){
  //Add Vue.js
  wp_enqueue_script('wpvue_vuejs');
  //Add my code to it
  wp_enqueue_script('my_vuecode');

  //Build String
  $str= "&lt;div id='divWpVue'&gt;"
  	."Message from Vue: {{ message }}"
  	."&lt;/div&gt;";

  //Return to display
  return $str;
} // end function

//Add shortcode to WordPress
add_shortcode( 'wpvue', 'func_wp_vue' );
?&gt;</code></pre>



<p class="has-small-font-size">Note: You can include the shortcode in a theme's functions.php file, it will still work the same as long as the the theme is being used, or its functions.php file isn't over-written with an upgrade.<br>I prefer the plugin because it separates out the style from the content and usually my Vue code is about content anyway.</p>
<p>More Info:<br><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://codex.wordpress.org/Functions_File_Explained" target="_blank">https://codex.wordpress.org/Functions_File_Explained</a><br><br>If you use the theme functions file, you need to call the file path in relation to your theme, not the plugin.</p>



<p>More Info:<br><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://codex.wordpress.org/Function_Reference/get_template_directory" target="_blank">https://codex.wordpress.org/Function_Reference/get_template_directory</a></p>



<p><strong>Download Files</strong></p>



<p>You can download the files at:  <br><a href="https://github.com/workingwebsites/wp-vue-tutorial" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">https://github.com/workingwebsites/wp-vue-tutorial</a> </p>



<h2>Conclusion</h2>



<p>Ok, so 'Hello Vue' doesn't exactly set the world on fire.  However, once you've got that in there, you can see how you can add a lot of functionality to your WordPress site through Vue.  </p>



<p>By using Vue in your WordPress site, accessing API's and making your site more interactive gets easier.  Likewise, if you have some crafty code written with Vue, dropping it into a WordPress site (and there's lots of them) is not a big trick.</p>



<p>Like peanut butter and jam, combining two good things make it better!</p>

{% endraw %}