Яндекс.Метрика
qr-код - Как-то так стрелка - Как-то так
Leading Economist + ... пиктограмма - Как-то Так THIS     Economic literacy and web solutions
All on the topic: what, how and why. Actual things - in their own words.
Turn your quality WITH ME - BUTW !
If you don't like what you get, change what you give. © Carlos Castaneda     KAKTOTAK.BY - economic design and web development services (php/js - telegram, WordPress, Laravel, Vue, SEO)    Cooperation - on an ongoing basis    Be in the topic   -    SUBSCRIBE      My notes are ECONOMICS +  и  WEB Developer's Guide | php+js+seo   в Telegram   telegram  

Creating a plugin for WordPress: Vue 3 and Ant Design for dynamic data display

Creating a plugin for WordPress: Vue 3 and Ant Design for dynamic data display

To understand the plugin development process on a popular engine WordPress together with the Vue 3 JS framework (composition api script setup syntax), let's look at a simple example where we implement server-side data output from a MySQL database to a client in an Ant Design table (a popular user interface development library).

We will also provide asynchronous server functionality for searching, sorting and paginating table data.

Let's take a detailed step-by-step look at the entire process of solving this problem:

Step 1: Install the necessary tools

Before we start, make sure that we have the following tools installed:

  • Node.js and npm: If we don't have them yet, download and install the software the official link. npm is installed together with Node.js .
  • Vite: It is a build tool that allows you to quickly develop and compile Vue applications. We will install it via npm.

Step 2: Creating the plugin folder structure

Let's create a folder structure for our plugin:

cd wp-content/plugins
mkdir my-custom-table-plugin
cd my-custom-table-plugin

Step 3: Create the main PHP plugin file

Creating a filemy-custom-table-plugin.php in this folder:

<?php
/**
 * Plugin Name: My Custom Table Plugin
 * Description: A plugin for displaying a table from a database using Vue 3 and Ant Design.
 * Version: 1.0
 * Author: Your Name
 */

// Protection against direct access
if (!defined('ABSPATH')) {
    exit;
}

// Enabling scripts and styles
function my_custom_table_plugin_enqueue_scripts() {
    wp_enqueue_script('my-vue-app', plugins_url('/dist/main.js', __FILE__), ['wp-element'], '1.0', true);
    wp_enqueue_style('ant-design', 'https://cdnjs.cloudflare.com/ajax/libs/antd/4.18.5/antd.min.css');
}

add_action('wp_enqueue_scripts', 'my_custom_table_plugin_enqueue_scripts');

// Rendering the component
function my_custom_table_plugin_render() {
    return '<div id="my-vue-app"></div>';
}

add_shortcode('my_custom_table', 'my_custom_table_plugin_render');

Step 4: Initialize the project with Vite and Vue

In the plugin folder (where we created my-custom-table-plugin), initialize the project using Vite:

npm init vite@latest client --template vue

This will create a new client folder with the Vue template.

Go to the client folder:

cd client

Install the dependencies:

npm install

Let's install Ant Design Vue:

npm install ant-design-vue

Step 5: Configure Vite

Now we need to configure Vite for proper assembly.

Open the filevite.config.js in the client folder and change it as follows:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

export default defineConfig({
    plugins: [vue()],
    build: {
OutDir: resolve(__dirname, '../dist'), // Compile to ../dist
        emptyOutDir: true,
        rollupOptions: {
            input: {
                main: resolve(__dirname, 'index.html'),
            },
        },
    },
});

Step 6: Creating a Vue Component

Now we will create a component that will display the table.

In the client/src/components/ folder, create the TableComponent.vue file and add the following code:

<template>
  <a-table
    :data-source="data"
    :pagination="pagination"
    :loading="loading"
    :columns="columns"
    @change="handleChange"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Table } from 'ant-design-vue';

const data = ref([]);
const loading = ref(true);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const columns = [
  {
title: 'Name',
    dataIndex: 'name',
    sorter: true,
  },
  {
title: 'Age',
    dataIndex: 'age',
    sorter: true,
  },
  {
title: 'City',
    dataIndex: 'city',
  },
];

const fetchData = async () => {
  loading.value = true;
  const response = await fetch(`/wp-json/myplugin/v1/data?page=${pagination.value.current}&pageSize=${pagination.value.pageSize}`);
  const result = await response.json();
  data.value = result.data;
  pagination.value.total = result.total;
  loading.value = false;
};

const handleChange = (pagination) => {
  pagination.value.current = pagination.current;
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

Step 7: Initialize our Vue application

Open the filemain.js in the client/src/ folder and import the new component and libraries:

import { createApp } from 'vue';
import App from './App.vue';
import TableComponent from './components/TableComponent.vue';
import 'ant-design-vue/dist/antd.css';

const app = createApp(App);
app.component('TableComponent', TableComponent);
app.mount('#my-vue-app');

Step 8: Configuring the REST API

In my-custom-table-plugin.php let's add the code for processing API requests (according to this principle, all APIs are created on the WordPress side):

add_action('rest_api_init', function () {
    register_rest_route('myplugin/v1', '/data', [
        'methods' => 'GET',
        'callback' => 'my_custom_table_api',
    ]);
});

function my_custom_table_api(WP_REST_Request $request) {
    global $wpdb;

    $page = $request->get_param('page') ?: 1;
    $page_size = $request->get_param('pageSize') ?: 10;

    $offset = ($page - 1) * $page_size;

    $results = $wpdb->get_results("SELECT name, age, city FROM your_table_name LIMIT $offset, $page_size");
    $total = $wpdb->get_var("SELECT COUNT(*) FROM your_table_name");
    
    return [
        'data' => $results,
        'total' => $total,
    ];
}

Let's not forget to replace your_table_name with the actual name of our table in the database.

Step 9: Compile the project

Now that everything is set up, we can compile the project:

Go to the client folder and run the command to build the project.:

npm run build

This will create a folder dist, which will contain the compiled files of our Vue application.

Step 10: Testing in Development mode

To work in development mode, run the command in the client folder:

npm run dev

This starts the Vite server, and our Vue application will be available at http://localhost:3000 (the port may be different).

Step 11: Checking the plug-in

  • Activate the plugin via the "Plugins" menu in the WordPress admin panel.
  • Insert the [my_custom_table] shortcode into any post or page.
  • Refresh the page and check the table.

Now, every time we access /wp-json/myplugin/v1/data, we get data from our database, and the data will be displayed in the Ant Design table.

Monitoring changes in development and production

Development mode:

When running npm run dev, we are working with a local Vite server. Changes to our components will be displayed automatically on the page if we save (update) it.

Production mode:

When compiling the project using npm run build, all our changes will be collected in the dist folder. After that, we will update our WordPress plugin to use the new versions of JS and CSS. You can simply refresh the page of the website where the [my_custom_table] shortcode is used to see the new changes.

Now our plugin is ready to use and reflect data from our database using Vue and Ant Design!

According to this principle, you can create full-fledged multifunctional SPA applications based on Vue using WordPress.

автор - Михаленко Р.
M R. Автор - kaktotak.by Specialization: financial and economic design - modeling of business, investment projects of the real sector, analysis and evaluation of efficiency, optimization of the management decision system.

A wide range of web-based competencies for solving business problems.

Subscribe to my telegram channel - My notes are ECONOMICS +
Там я ничего не втюхиваю и не навязываю. Просто делюсь полезной информацией по экономической грамотности. Повышайте своё качество вместе со мной: что, как и почему в экономике на простом языке. Понятия, алгоритмы, процессы, микро- и макроаспекты и многое другое. Может, будет интересно !

And also - WEB Developer's Guide | php+js+seo
Notes and native solutions to simple local tasks in PHP, JS. Something about Laravel, WordPress, Vue and SEO.

  Personal assistance in economic design and web development:

  • Financial and economic modeling, analysis, accounting, business planning
  • Comprehensive web development/project support on the web (php/js, seo – Laravel, WordPress, Vue, telegram, administration, content, advertising in Yandex Direct

  telegram или форма обратной связи

Administrator
177

Currency Converter
RUB RUB-icon
USD USD-icon
EUR EUR-icon
CNY CNY-icon
BYN BYN-icon
UAH UAH-icon
KZT KZT-icon
SHORT- what is it about
ECONOMIC LITERACY
  Simple online solutions to problems of economics and finance  
I Want To Know Everything. Useful Tips