This tutorial shows how to build a modern WordPress UI using Vue.js, a progressive JavaScript framework. We'll create a simple plugin with a Vue interface interacting with the WordPress REST API via the Fetch API.
Key Concepts:
/wp-json/wp/v2/posts?filter[orderby]=date
endpoint to display recent posts.mounted()
, and fetching data. Real-time updates using setInterval()
will also be shown.Building the WordPress Plugin:
Create Plugin Directory: Create a folder (e.g., vueplugin
) within your WordPress wp-content/plugins
directory.
vueplugin.php
: Inside the folder, create vueplugin.php
with the following initial content:
<?php /* Plugin Name: Latest Posts Description: Latest posts shortcode with Vue.js Version: 1.0 */
Register Shortcode: Add this code to vueplugin.php
to register a shortcode named latestPosts
:
function handle_shortcode() { return '<div id="mount"></div>'; } add_shortcode('latestPosts', 'handle_shortcode'); 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'); wp_enqueue_script('latest-posts', plugin_dir_url(__FILE__) . 'latest-posts.js', [], '1.0', true); } } add_action('wp_enqueue_scripts', 'enqueue_scripts');
This enqueues the Vue.js library and a custom JavaScript file (latest-posts.js
).
Activate Plugin: Activate the plugin via your WordPress admin dashboard.
Test Shortcode: Add [latestPosts]
to a post or page to test the shortcode.
Integrating Vue.js:
latest-posts.js
: Create latest-posts.js
in your plugin directory with this code:
(function() { var vm = new Vue({ el: '#mount', data: { posts: [] }, mounted: function() { this.fetchPosts(); setInterval(this.fetchPosts.bind(this), 5000); }, methods: { fetchPosts: function() { fetch('/wp-json/wp/v2/posts?filter[orderby]=date') .then(response => response.json()) .then(data => this.posts = data); } }, template: ` <div> <h1>My Latest Posts</h1> <div v-if="posts.length > 0"> <ul> <li v-for="post in posts"> <a :href="https://www.php.cn/link/f417d05af72b37f956c906aea42d1511">{{ post.title.rendered }}</a> </li> </ul> </div> <div v-else> <p>Loading posts...</p> </div> </div> ` }); })();
This Vue instance fetches posts, displays them in a list, and updates every 5 seconds.
latest-posts.js
script should also be included in your page source.
Conclusion:
This enhanced tutorial provides a complete, working example of integrating Vue.js into a WordPress plugin for a dynamic, real-time user experience. Remember to adjust paths and styling as needed for your specific theme. The FAQs from the original input have been omitted as they are adequately covered within the revised and expanded tutorial.
The above is the detailed content of Building a WordPress Plugin with Vue. For more information, please follow other related articles on the PHP Chinese website!