How to Build or Develop WordPress Plugin With vue.JS Library

Vue.js

vue.JS LibraryVue.js is an exceptionally popular JavaScript library in development for building current and rich user interfaces similar to Angular and React as far as popularity, performance, and component-based architecture. In this article, we will explore the most common way of building and developing an exceptionally basic WordPress plugin with a Vue.js interface that interacts with the WordPress REST API via the JavaScript Fetch API.

We will create a shortcode that will allow us to add the latest published present gadget on our WordPress website. The gadget UI is a Vue app that gets the latest published posts via the/wp-json/wp/v2/posts?filter[orderby]=date WP-API endpoint.

This tutorial explores the basics of Vue.js. We’ll perceive how to create an instance of Vue, use lifecycle snares like mounted() as well as the JavaScript Fetch API to interact with the WordPress REST API.

More From us:What is the uninstall.php file in WordPress

Building a WordPress plugin with Vue.js

In this section, we will perceive how to create a WordPress plugin that registers a shortcode in a couple of steps.

Create a folder in wp-content/plugins

We should start by creating the back-end part of our plugin. Plugins are located in the wp-content/plugins folder. Go to this folder in your WordPress installation folder and create a subfolder for your plugin. We should call it Vue plugin.

cd /var/www/html/wp-content/plugins

mkdir vueplugin

Inside your plugin folder, create a vueplugin.php file and add the basic content:

<?php

/*

Plugin Name: Latest Posts

Description: Latest posts shortcode

Version: 1.0

*/

These remarks are used as meta information for the plugin. In this example, we essentially give the plugin name, description, and version. If you visit the plugins page in the admin panel, you ought to have the option to see your plugin listed:

Create a shortcode

Shortcodes are used through WordPress plugins to allow users to add content to posts and pages. To register the shortcode, you should add at least the following code in your plugin file:

function handle_shortcode() {

    return ‘My Latest Posts Widget’;

}

add_shortcode(‘latestPosts’, ‘handle_shortcode’);

In this part of the tutorial on creating a WordPress plugin with Vue.js, we are registering a short code called last posts.

WordPress worked in the add_shortcode() function using vue.js gives the ability to create shortcodes in your WordPress plugin. This function takes a name as the primary parameter and the handler function that processes your shortcode rationale and returns the result as the second parameter.

At this point, we’ll simply return a static string from our shortcode, yet shortcodes are most useful when used to insert dynamic content. Now how about we activate the plugin from the admin panel by clicking on the activation link beneath the plugin name

You can use a shortcode by enclosing it in square brackets – ie [SHORTCODE_NAME]. The text inside the parentheses is the name we gave as the main parameter to the add_shortcode() function. It is replaced by the result returned by the PHP function passed as the second parameter.

To test if our shortcode was effectively registered, we can create another post and add [latestPosts] to the post content

You ought to see the sentence gadget of my last posts:

Now, instead of displaying the static My Recent Posts gadget string, we should display the latest posts using Vue.js.

Vue.js integration with WordPress plugin

The Vue documentation lists different ways to use Vue.js. The easiest way is to use the tag to include the content library, which is also the easiest way to integrate Vue.js with WordPress.

You can integrate a Vue app with WordPress in a couple of basic steps:

  • First, you really want to add a DOM component in WordPress (for example via a shortcode) where you can install the Vue app.
  • Then, you really want to line the Vue library script.
  • Finally, you want to create a Vue application in a separate JavaScript file and line it.

Not at all like the traditional approach of using WordPress, using Vue.js allows you to add interaction and a superior user experience. Instead of having to reload the ongoing page, users can interact with the page and update the interface dynamically.

WordPress apps or plugins created with Vue.js are called SPAs or Single Page Apps. However, in our example, instead of creating a full SPA, we’ll use Vue.js to create a basic gadget that can be used to give information on a small part of your page (like a sidebar). Think of a gadget created with Vue.js as a small SPA.

We should start by putting the Vue library in WordPress. We really want to add one more function to our plugin that handles the queueing of the Vue library:

function enqueue_scripts(){

   global $post;

   if(has_shortcode($post->post_content, "latestPosts")){

                wp_enqueue_script('vue', 'https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js', [], '2.5.17');

   }           

}

In the first place, we verify whether we’re displaying a post that contains the shortcode for our latest posts, then we enqueue the Vue script using the wp_enqueue_script() function. You can check if the content is included by looking at the source code of your post

Then, return to the handle_shortcode() function and change it to a <div> so we can deliver a Vue app:

<div id="mount"></div>

Then, create a lastposts.js file in your plugin folder and add the following code to create a Vue instance:

( function() {

  var vm = new Vue({

    el: document.querySelector('#mount'),

    mounted: function(){

      console.log("Hello Vue!");

    }

  });

})();

We create another Vue instance with the Vue() function, which is the initial step to start the Vue application. While creating a Vue instance, you should also give an options object, which allows you to give various options to building your Vue application.

In this example, we use the el property to give the Vue instance of an existing DOM component to mount on. This can be a CSS selector or an actual HTMLElement. In our example we use document.querySelector(‘#mount’) to get the HTML component

with id #mount.

We also use the mounted attribute to give a function that will be called after the instance is mounted. At this point, we’re simply registering a Hello Vue! The string is printed on the console.

You can also check the full list of available options in this library’s API reference. In the following stage of building a WordPress plugin, very much like working with the Vue.js library, you want to line this file. Add the following code inside the enqueue_scripts() function:

wp_enqueue_script('latest-posts', plugin_dir_url( __FILE__ ) . 'latest-posts.js', [], '1.0', true);

The underlying function plugin_dir_url() is used to get the absolute URL of a file. __FILE__ is a constant variable that gives you the file framework path of the ongoing PHP file. This allows us to get the absolute path to the latest-posts.js file without using hard-coded URLs that can be changed on another framework.

At this point, you ought to see Hello Vue! String in the program console

And you ought to also see the latest-posts.js script in the source code of a post that contains the shortcode.

Then, we should change the WordPress plugin build to deliver the past My Latest Posts Widget thread, yet this time through Vue.js. In your Vue instance, add the template attribute with any HTML code you want to deliver.

var vm = new Vue({

   el: document.querySelector('#mount'),

   template: "<h1>My Latest Posts Widget</h1>",

   mounted: function(){

   console.log("Hello Vue!");

 }

});

Now, how about we get and deliver the latest posts using the get API. In the Vue example, add a data property with the post array that holds the recovered posts:

var vm = new Vue({

   el: document.querySelector('#mount'),

   data: {

    posts: []

   },

Then, we should add code to get the latest posts in the installed lifecycle occasion that fires when the component is installed on the DOM:

var url = '/wp-json/wp/v2/posts?filter[orderby]=date';

 fetch(url).then((response)=>{

    return response.json()

  }).then((data)=>{

    this.posts = data;

  })

We call JavaScript’s bring() method, which returns a Promise. After the promise settles effectively, we assign the data to the posts array. Finally, add the template attribute.

template: `<div><h1>My Latest Posts</h1>

  <div>

    <p v-for="post in posts">

      <a v-bind:href="post.link">{{post.title.rendered}}</span></a>

    </p>

  </div>

</div>

We use the Vue v-for command to circle through the posts and display the title. rendered and link properties of each post. Here is a screen capture of the outcome for me.

In your case, it may appear to be unique depending on your active theme and the posts you have on your WordPress website.

If you click on the post title, you ought to be diverted to the posting page. We can add more features to our gadget, for example, real-time data fetching, so the user doesn’t have to reload the page to recover the latest published posts. We can achieve this by continuously polling the WP-AP I endpoint using the JavaScript setInterval() method.

To start with, pass the code that gets the posts in its own particular manner:

var vm = new Vue({

  /*...*/




 methods:{




  fetchPosts: function(){

    var url = '/wp-json/wp/v2/posts?filter[orderby]=date';

    fetch(url).then((response)=>{

      return response.json()

      }).then((data)=>{

        this.posts = data;

        console.log(this.posts);

      });

  }

 },

We use the Vue instance methods feature to add custom methods to the Vue instance. You can then access these methods straightforwardly on the instance via this.

Then, in the mounted() function, add the following code to get posts like clockwork.

var vm = new Vue({

  /*...*/

 mounted: function() {

   console.log("Component is mounted");




   this.fetchPosts();

   setInterval(function () {

    this.fetchPosts();

   }.bind(this), 5000);

 }

You can test this section by opening the WordPress admin panel in another program tab and adding another post. You ought to update your Vue gadget with another post without manually refreshing the page.

Conclusion

In this tutorial, we saw how to build a WordPress plugin that uses the Vue.js library. We’ve created a shortcode that can be used to display a Vue component on your posts and pages that will bring and display the latest posts like clockwork. This is achieved through polling the WordPress REST API using the setInterval() method.

 

Leave a comment

Your email address will not be published.