Prepare user data
//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; }
Transfer user data
function vuespa_data() { $person = [ "str" => "Hello, world! - Npcink", "num" => 25, "city" => [1, 2, 3, 4, 5], "user" => vuespa_get_user_meat(), ]; return $person; }
JS Preparation Page
//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");
-
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
//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)); } }
use
echo get_option('dataName');
summary
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");