Section 3: Vue3 develops WordPress setting options - research the front and rear data interaction from the filtering function

In this section, we get the user list data from WordPress and render it on the page through Vue3. We also modified the interface for saving options to save array type data

Following the above, we have made a simple setting option with two input boxes and a save button. Now, it can implement the basic filling information and save it to the WordPress background for PHP to call the option value.

Now, let's go further and add the personnel filtering function to it. Let's make the following box, select from it by user name, and provide the selected user ID to the backend through an array. The general process is as follows

 Section 3: Vue3 develops WordPress setting options - research the front and rear data interaction from the filtering function

The final effect is as follows

 Section 3: Vue3 develops WordPress setting options - research the front and rear data interaction from the filtering function

Prepare user data

Generally, websites have a large number of users, most of whom are "subscribers". In order to reduce the pressure of transmitting data, we exclude them when obtaining user data
In order to make it easy for JS to use the data and reduce the difficulty of using the data by JS, we organize it into the following structure

 Section 3: Vue3 develops WordPress setting options - research the front and rear data interaction from the filtering function

stay vue-spa.php Add the following code at the bottom of the file

 //Organize and provide user information function vuespa_get_user_meat() { //Get all roles $editable_roles = wp_roles()->roles; $roles = array_keys($editable_roles); //Get the user data of all roles except the 'subscriber' role $subscriber_key = array_search('subscriber', $roles, true); if (false !== $ subscriber_key) { $roles = array_slice($roles, 0, $subscriber_key); } $users = get_users(array('role__in' => $roles)); //Convert to associative array $user_data = array_map(function ($user) { return [ 'id'   => $user->ID, 'name' => $user->display_name, ]; }, $users); return $user_data; }

You can refer to this method to perform classification filtering, article filtering, label filtering and other filtering functions. You only need to provide data by structure.

Transfer user data

We pass the data to JS through PHP for use, and we modify vue-spa.php In file vuespa_data() Function, change to the following

 function vuespa_data() { $person = [ "str" => "Hello, world! - Npcink", "num" => 25, "city" => [1, 2, 3, 4, 5], "user" => vuespa_get_user_meat(), ]; return $person; }

Refresh the menu page, and we can see the effect as shown in the above figure.

JS Preparation Page

Get the data from JS and render it to the page. Modify index.js to the following

 //vite/dist/index.js console.log(dataLocal.data.user); const App = { setup() { //Store the value transmitted const siteData = dataLocal.data; //Store option values const datas = Vue.reactive({ dataOne: "", dataTwo: "", dataName: [], }); //Get Data const vuespa_get_option = () => { axios .post(dataLocal.route + "pf/v1/get_option", datas, { headers: { "X-WP-Nonce": dataLocal.nonce, "Content-Type": "application/json", }, }) .then((response) => { const data = response.data; datas.dataOne = data.dataOne; datas.dataTwo = data.dataTwo; datas.dataName = data.dataName; }) .catch((error) => { Window.alert ("Failed to connect to the server or background reading error! Data reading failed"); console.log(error); }); }; //Omit some codes return { datas,  siteData, vuespa_update_option }; }, template: ` Text box 1:<input type="text" v-model="data. dataOne"><br/> Textbox 2:<input type="text" v-model="data. dataTwo"><hr/> User selection:<select v-model="data. dataName" multiple> <option v-for="option in siteData.user" :key="option.id" :value="option.id"> {{ option.name }} </option> </select> <p>You have selected: {{data. dataName}}</p><br/> Press and hold the command (control) button to make multiple selections<hr/> <button class="button button primary" @ click="vuespa_update_option">Save</button>`, }; Vue.createApp(App).mount("#vuespa");

To help you see the difference, I have omitted some unmodified code. See the previous section for details.
The main contents are as follows

  • New Variable siteData Store the transmitted data
  • New Array Variable dataName Store the selected array
  • In the process of obtaining data, use the datas.dataName = data.dataName; Get default value

Modify Save Interface

The original save interface cannot recognize the array. If you modify the selected value and click Save, the selected value will be lost after the page is refreshed.

modify interface.php Save Options Function of Articles update_option_by_RestAPI() For

 //Save Option function update_option_by_RestAPI($data) { //Judge whether it is an administrator if (current_user_can('manage_options')) { //Convert to JSON object - key point, there is no true here, it is converted to object $dataArray = json_decode($data->get_body()); //Store Results $result = new stdClass(); //Cycle Save Options foreach ($dataArray as $option_name => $value) { //Judge whether it is an object if (is_object($value)) { //It is a non empty array, and the value is saved circularly foreach ($value as $arr => $data) { //Update values update_option($arr, $data); } } else { //If it is not an object, it means that only one option needs to be saved. update_option($option_name, $value); } $result->$option_name = $value; } //Return success message return new WP_REST_Response(array( 'success' => true, 'message '=>"Saved!" ), 200); } else { //Return failure information Return new WP_Error ('save_error ','save failed!', array('status' => 500)); } }

The function of this function can be seen in the comments. Now, refresh the page, filter in the following list, and click Save to refresh the page. You can see that the value is saved normally,

use

At this point, you can use the get_option Get the values in the options in PHP, as mentioned in the previous section.

 echo get_option('dataName');

Note that this shows the array ID

summary

In this section, we added the drop-down list multi selection function, which did not solve the problem mentioned in the previous section. Don't worry. I find it convenient to display the function types at present. I plan to solve the problem mentioned in the previous section after showing all common function types.

Document code

vue-spa.php

 <? php /* Plugin Name: Vue - SPA  Plugin URI:  https://www.npc.ink Description: Embed the page built by vue into WordPress and generate interaction Author: Muze Author URI:  https://www.npc.ink Version: 1.0.0 */ //Interface require_once plugin_dir_path(__FILE__) . ' interface.php'; //Create a menu function vuespa_create_menu_page() { add_menu_page( 'VueSpa option',//This menu corresponds to the title displayed on the page 'VueSpa',//The text to be displayed for this actual menu item 'administrator',//which type of user can see this menu 'vuespa_id',//The unique ID of this menu item (i.e. slug) 'vuespa_menu_page_display',//Name of the function to be called when presenting the menu of this page 'dashicons admin customizer ',//icon - default icon '500.1',//Location ); } // end vuespa_create_menu_page  add_action('admin_menu', 'vuespa_create_menu_page'); //Menu callback - displayed content function vuespa_menu_page_display() { ?> <!-- Create a title in the default WordPress "wrapper" container --> <div class="wrap"> <!-- Title --> <h2><? php echo esc_html(get_admin_page_title()); ?></ h2> <!-- Provide Vue mount point --> <div id="vuespa">This content will be replaced after mounting Vue {{data}}</div> </div> <? php //Show prepared data echo "<pre>"; print_r(vuespa_data()); echo "</pre>"; Echo "<h3>Call option value</h3>"; echo get_option('dataOne'); echo "<br/>"; echo get_option('dataTwo'); } // vuespa_menu_page_display //Load the required JS and CSS resources and transfer data function vuespa_load_vues($hook) { //Judge whether the current page is the specified page. If yes, continue loading if ('toplevel_page_vuespa_id' != $ hook) { return; } //Version No $ver = '53'; //Load to top of page wp_enqueue_style('vite', plugin_dir_url(__FILE__) . ' vite/dist/index.css', array(), $ver, false); //Load to bottom of page wp_enqueue_script('vue', ' https://unpkg.com/vue @3/dist/vue.global.js', array(), $ver, true); wp_enqueue_script('axios', ' https://unpkg.com/axios/dist/axios.min.js ', array(), $ver, true); wp_enqueue_script('vite', plugin_dir_url(__FILE__) . ' vite/dist/index.js', array(), $ver, true); $pf_api_translation_array = array( 'route'=>esc_url_raw (rest_url()),//Route 'nonce'=>wp_create_once ('wp_rest '),//Verification mark 'data '=>vuespa_data(),//user-defined data ); wp_localize_script('vite', 'dataLocal', $pf_api_translation_array); // Transfer to vite project } //Load style to background add_action('admin_enqueue_scripts', 'vuespa_load_vues'); //Prepare the data to be transmitted function vuespa_data() { $person = [ "str" => "Hello, world! - Npcink", "num" => 25, "city" => [1, 2, 3, 4, 5], "user" => vuespa_get_user_meat(), ]; return $person; } //Organize and provide user information function vuespa_get_user_meat() { //Get all roles $editable_roles = wp_roles()->roles; $roles = array_keys($editable_roles); //Get the user data of all roles except the 'subscriber' role $subscriber_key = array_search('subscriber', $roles, true); if (false !== $ subscriber_key) { $roles = array_slice($roles, 0, $subscriber_key); } $users = get_users(array('role__in' => $roles)); //Convert to associative array $user_data = array_map(function ($user) { return [ 'id'   => $user->ID, 'name' => $user->display_name, ]; }, $users); return $user_data; }

interface.php

 <? php //interface.php //Interface document function vuespa_create_api() { Register_rest_route ('pf/v1 ','/get_option/', array (//The full namespace is:/wp-json/pf/v1/ 'methods' => 'POST', 'callback' => 'get_option_by_RestAPI', )); Register_rest_route ('pf/v1 ','/update_option/', array (//The full namespace is:/wp-json/pf/v1/ 'methods' => 'POST', 'callback' => 'update_option_by_RestAPI', 'permission_callback' => function () { return current_user_can('manage_options'); //  Only administrators have permission to modify }, )); } add_action('rest_api_init', 'vuespa_create_api'); //Read Option //Only one-to-one data requests are supported function get_option_by_RestAPI($data) { //Convert the passed data to array type $dataArray = json_decode($data->get_body(), true); //New Array $return = array(); //Loop to obtain the value of the corresponding option ID and store it in the corresponding associative array. If the value cannot be obtained, it is empty foreach ($dataArray as $option_name => $value) { $return[$option_name] = get_option($option_name) ?  get_option($option_name) : ""; } return $return; } //Save Option function update_option_by_RestAPI($data) { //Judge whether it is an administrator if (current_user_can('manage_options')) { //Convert to JSON object - key point, there is no true here, it is converted to object $dataArray = json_decode($data->get_body()); //Store Results $result = new stdClass(); //Cycle Save Options foreach ($dataArray as $option_name => $value) { //Judge whether it is an object if (is_object($value)) { //It is a non empty array, and the value is saved circularly foreach ($value as $arr => $data) { //Update values update_option($arr, $data); } } else { //If it is not an object, it means that only one option needs to be saved. update_option($option_name, $value); } $result->$option_name = $value; } //Return success message return new WP_REST_Response(array( 'success' => true, 'message '=>"Saved!" ), 200); } else { //Return failure information Return new WP_Error ('save_error ','save failed!', array('status' => 500)); } }

index.js

 //vite/dist/index.js console.log(dataLocal.data.user); const App = { setup() { //Store the value transmitted const siteData = dataLocal.data; //Store option values const datas = Vue.reactive({ dataOne: "", dataTwo: "", dataName: [], }); //Get Data const vuespa_get_option = () => { axios .post(dataLocal.route + "pf/v1/get_option", datas, { headers: { "X-WP-Nonce": dataLocal.nonce, "Content-Type": "application/json", }, }) .then((response) => { const data = response.data; datas.dataOne = data.dataOne; datas.dataTwo = data.dataTwo; datas.dataName = data.dataName; }) .catch((error) => { Window.alert ("Failed to connect to the server or background reading error! Data reading failed"); console.log(error); }); }; //Save Data const vuespa_update_option = () => { axios .post(dataLocal.route + "pf/v1/update_option", datas, { headers: { "X-WP-Nonce": dataLocal.nonce, }, }) .then((response) => { Alert ("saved successfully"); }) .catch((error) => { Alert ("Failed to save"); console.log(error); }); }; //Page initial loading Vue.onMounted(() => { Console.log ("Simple"); vuespa_get_option(); }); return { datas,  siteData, vuespa_update_option }; }, template: ` Text box 1:<input type="text" v-model="data. dataOne"><br/> Textbox 2:<input type="text" v-model="data. dataTwo"><hr/> User selection:<select v-model="data. dataName" multiple> <option v-for="option in siteData.user" :key="option.id" :value="option.id"> {{ option.name }} </option> </select> <p>You have selected: {{data. dataName}}</p><br/> Press and hold the command (control) button to make multiple selections<hr/> <button class="button button primary" @ click="vuespa_update_option">Save</button>`, }; Vue.createApp(App).mount("#vuespa");
course

Section 2: Vue3 develops WordPress setting options - start from the input box and configure basic setting options

2023-6-27 22:29:00

course

Section 4: Vue3 develops WordPress setting options - add image upload function

2023-6-28 22:02:00

⚠️
Some codes and tutorials on Npcink come from the Internet, and are only for netizens to learn and exchange. If you like this article, you can Attach original link Reprint at will.
No intention of infringing your rights, please send an email to 1355471563#qq.com Or click on the right Private message: Muze feedback, we will deal with it as soon as possible.
0 replies A Author M administrators
    There is no discussion yet. Tell me your opinion
Personal Center
Shopping Cart
Coupon
Sign in today
There are new private messages Private Message List
search