WordPress

WordPress with Angular

AngularJS is a JavaScript framework. It is a library written in JavaScript. AngularJS can be added to a web page using the <script> tag. AngularJS extends HTML attributes with directives. This tutorial will focus on CRUD (Create, Read, Update and Delete Delete) operations with AngularJS in WordPress.

We will implement the following functions:

  • Retrieve user data from the database using WordPress and MySQL, and display user data using AngularJS.
  • Add user data to the database using AngularJS, WordPress, and MySQL.
  • Delete user data from the database using AngularJS, WordPress, and MySQL.

Before you start AngularJS CRUD right now, you need WordPress JSON. So we will create a basic plugin to get JSON data.

To create a plugin, navigate to the “wp-content / plugins” folder, and create a new folder named “WPJationAngular“. Inside this new folder, create a file named “WPJsonAngular.php“. Open the file in the text editor, and paste the following code:

<?php
   /*
   Plugin Name: AngularCRUD
   Plugin URI: http://Angular-CRUD.com
   description:  CRUD operation with angular
   Version: 1.0
   Author: Mr. Kejal
   Author URI: 
   License: GPL2
   */?>

All this information, only the plugin name is required. But if you want to describe your plugin, you should add as much data as possible.

1. Creating Custom Table

function create_plugin_database_table()
{ 
    global $table_prefix, $wpdb;

    $tblname = 'AngularJson';
    $wp_track_table = $table_prefix ."$tblname";

    #Check to see if the table exists already, if not, then create it

    if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table) 
    {
        
        $sql = "CREATE TABLE `".$wp_track_table."` ( ";
        $sql .= "  `id`  int(11)   NOT NULL auto_increment, ";
        $sql .= "  `firstname` varchar(128)   NOT NULL, ";
        $sql .= "  `lastname` varchar(128)   NOT NULL, ";
        $sql .= "  `email` varchar(128)   NOT NULL, ";
        $sql .= "  PRIMARY KEY (`id`) "; 
        $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";

        require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
        dbDelta($sql);
    }
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );

2. Now, use “register_rest_route” to generate the JSON data URL.

// get data using GET method
add_action('rest_api_init', function () {
    register_rest_route( 'api/v1', '/user', array(
        'methods' => 'GET',
        'callback' => 'get_user_from_data'
    ));
});
function get_user_from_data() {
    global $wpdb;
    $results = $wpdb->get_results( "SELECT * FROM wp_angularjson");
    print json_encode($results);
}

// insert data using POST method
add_action('rest_api_init', function () {
    register_rest_route( 'api/v2', '/user', array(
        'methods' => 'POST',
        'callback' => 'insert_user_from_data'
    ));
});
function insert_user_from_data() {
    global $wpdb;
    $table='wp_angularjson';

    $wpdb->insert($table, array(
        'firstname' => $_POST['firstname'],
        'lastname' => $_POST['lastname'],
        'email' => $_POST['email'],
    ));
}

// Delete data using DELETE method
add_action('rest_api_init', function () {
    register_rest_route( 'api/v3', '/user', array(
        'methods' => 'POST',
        'callback' => 'delete_user_from_data'
    ));
});
function delete_user_from_data() {
    global $wpdb;
    $table='wp_angularjson';

    $id = $_POST['id'];
    $wpdb->delete( $table, array( 'id' => $id ) );
}

3. Creating a menu

add_action('admin_menu','angular_json_add_menu');

In the callback function, you have to write what you want to alter in the admin menu.

function angular_json_add_menu(){
  add_menu_page(
    'Angular Json',
    'Angular Json',
    'manage_options',
    'angular-json-form',
    'get_post_api',
    'dashicons-book',
    16,
  );
}

As you can see in angular_json_add_menu() function I just used add_menu_page(). This function allows you to create a menu in the admin sidebar and map that menu to a page.

4. With the use of get_post_api() function display the JSON URL and inserted data. We will use the JSON URL in Angular.

function get_post_api(){
    $site_url = site_url();
    echo '<h4> Json Get data</h4>';
    echo '<input type="text" size="50" readonly value="'.$site_url.'/wp-json/api/v1/user" />';
    echo '<h4> Json Insert data</h4>';
    echo '<input type="text" size="50" readonly value="'.$site_url.'/wp-json/api/v2/user" />';
    echo '<h4> Json Delete data</h4>';
    echo '<input type="text" size="50" readonly value="'.$site_url.'/wp-json/api/v3/user" />';
    echo '<br /><br />';
    get_post_data(); // Get Data
}

function get_post_data(){
    global $wpdb;
    $results = $wpdb->get_results( "SELECT * FROM wp_angularjson");

    echo '<table border="1" cellpadding="10">';
        echo '<tr>';
            echo '<th> ID </th>';
            echo '<th> FirstName </th>';
            echo '<th> LastName </th>';
            echo '<th> Email </th>';
        echo '</tr>';

        foreach($results as $row){
        ?>
            <tr>
                <td><?php echo $row->id; ?></td>
                <td><?php echo $row->firstname; ?></td>
                <td><?php echo $row->lastname; ?></td>
                <td><?php echo $row->email; ?></td>
            </tr>
        <?php
        }

    echo '</table>';
}

 

Now, let’s added a JSON URL in your angular JS file code.

1. Write down the menu code in the component HTML file to generate the menu. (app.component.html)

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" [routerLink]="['']">Therichpost</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" [routerLink]="['']" >Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" [routerLink]="['/users']" >Users</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" [routerLink]="['/adduser']" >Add User</a>
        </li>
       
      </ul>
    </div>
  </div>
</nav>
<router-outlet></router-outlet>

Generate the routing file to route the menu.

1.1 Write down the code in the routing file. (app-routing.module.ts)

import { NgModule } from '@angular/core';
import { UsersComponent } from './users/users.component';
import { AdduserComponent } from './adduser/adduser.component';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
  { path: '', component: UsersComponent },
  { path: 'users', component: UsersComponent },
  { path: 'adduser', component: AdduserComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Generate a component to add a user.

2. Write down the code in the component HTML file to create the form. (adduser.component.html)

<div class="container p-5">
    <h1 class="text-left mb-5">Add User</h1>
  <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
    <div class="row">
       <div class="col-sm-6">
          <div class="form-group">
                <label>Firstname</label>
                <input type="text" formControlName="firstname" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstname.errors }" />
                <div *ngIf="submitted && f.firstname.errors" class="invalid-feedback">
                      <div *ngIf="f.firstname.errors.required">FirstName is required</div>
                </div>
             </div>
       </div> 
       <div class="col-sm-6">
        <div class="form-group">
              <label>Lastname</label>
              <input type="text" formControlName="lastname" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastname.errors }" />
              <div *ngIf="submitted && f.lastname.errors" class="invalid-feedback">
                    <div *ngIf="f.lastname.errors.required">LastName is required</div>
              </div>
           </div>
     </div> 
       <div class="col-sm-6">
          <div class="form-group">
             <label>Email</label>
             <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
             <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
                <div *ngIf="f.email.errors.required">Email is required</div>
                <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
             </div>
          </div>
       </div>
       
       
   </div>
   <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  </div>

2.1 Write down the code in the same component TS file to call the service file function. (adduser.component.ts)

import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CrudService } from '../crud.service'; 
import { Router } from '@angular/router';
@Component({
  selector: 'app-adduser',
  templateUrl: './adduser.component.html',
  styleUrls: ['./adduser.component.css']
})
export class AdduserComponent implements OnInit {
// @Input
registerForm! : FormGroup;

submitted = false;
constructor( private crudservice: CrudService, private formBuilder: FormBuilder, private router: Router){}
//Add user form actions
get f() { return this.registerForm.controls; }
onSubmit() {
  
  this.submitted = true;
  // stop here if form is invalid
  if (this.registerForm.invalid) {
      return;
  }
  //True if all the fields are filled
  if(this.submitted)
  {
    
    // Initialize Params Object

     var myFormData: any = new FormData();
  
   // Begin assigning parameters
      myFormData.append('firstname', this.registerForm.value.firstname);
      myFormData.append('lastname', this.registerForm.value.lastname);
      myFormData.append('email', this.registerForm.value.email);

      this.crudservice.adduser(myFormData); //calling add user service
      this.router.navigate([`/users`]); //after form submit page will redirect to users page
  }
 
}
  ngOnInit() {
    //Add User form validations
    this.registerForm = this.formBuilder.group({
      firstname: ['', [Validators.required]],
      lastname: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]]
    });
  }
}

Generate a service to insert user data.

3. Write down the code in the service file to call the add user function. (crud.service.ts)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CrudService {
  userData:any;
  constructor(private http:HttpClient) { }
  //get all users  details
  public getusers()
  {
    return this.http.get('http://localhost/wordpress-api/wp-json/api/v1/user');
  }
  //add new user    
  public adduser(myFormData:any)
  {
    return this.http.post('http://localhost/wordpress-api/wp-json/api/v2/user'
    , myFormData).subscribe((myFormData: any) => {
    this.getusers();
    });
  }

}

Now, Generate another component to retrieve and delete the user.

4. Write down the code in the component HTML file to retrieve and delete the user. (user.component.html)

<div class="container p-5">
    <h1>Users</h1>
    <table class="table table-hover table-bordered">
        <thead>
          <tr>
            <th>ID</th>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
            <tr *ngFor="let group of data">
            <td>{{group.id}}</td>
            <td>{{group.firstname}}</td>
            <td>{{group.lastname}}</td>
            <td>{{group.email}}</td>
            <td><button class="bg-danger" (click)="deleteuser(group.id)"> Del</button></td>
            </tr>
        </tbody>
      </table>
</div>

4.1 Write down the code in the same component TS file to call the service file function. (user.component.ts)

import { Component, OnInit } from '@angular/core';
import { CrudService } from '../crud.service';


@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  data : any = [];
  constructor( private crudservice: CrudService){
   //Get all usera details  
    this.loaddata();
  }
  //Get all users data
  loaddata()
  {
    //Get all usera details  
    this.crudservice.getusers().subscribe((res: any)=>{
      this.data = res;
    });
  }

  //Delete User
  deleteuser(id:any)
  {
    if(confirm("Are you sure to delete?")) {
      
      // Initialize Params Object
      var sendId = new FormData();

      // Begin assigning parameters
      sendId.append('id', id);

      this.crudservice.deleteusers(sendId);

      this.loaddata();
    }
  }
  ngOnInit(): void {
     
  }
}

5. Write down the code in the already generated service file to call the delete user function. (crud.service.ts)

public deleteusers(sendId:any)
  {
    return this.http.post('http://localhost/wordpress-api/wp-json/api/v3/user'
    , sendId).subscribe((sendId: any) => { 
      this.getusers();
    });
  }

 

Now that’s it. Run the project and the output will look somewhat like this.

 

kejal patel

I am a Web Developer with 5 years of experience specializing in WordPress customization.

Share
Published by
kejal patel

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago