Create WordPress like add tags using Codeigniter and jQuery

I will show you how to create WordPress like add tags using Codeigniter and jQuery. This add tags tutorial example is very helpful to implement the multiple tags adding functionality for a blog. In this example, tags are added to the textarea just by “type and press the Enter key”.

Codeigniter controller stores tags into the database table and returns response as success or failure message from the controller. As a validation step I have added one step to check if you have input at least one tag.

Prerequisites

Apache 2.4, Codeigniter 3.1.10, PHP 7.3.5, MySQL 5.6

Example with Source Code

Creating Project Directory

We need to first create our root project directory in order to implement the WordPress like tags using Codeigniter framework.

It’s assumed that you have setup Apache 2.4, PHP 7.3.5 and Codeigniter 3.1.10 in Windows system.

Next we will create a project root directory called codeIgniter-3.1.10-wordpress-tags under the Apache server’s htdocs folder.

Now move all the directories and files from Codeigniter 3.1.10 framework into codeIgniter-3.1.10-wordpress-tags directory.

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Autoload Configuration

We need some configurations, such as, auto-loading for database, helpers etc. to avoid loading every time we need to use.

Modify application/config/autoload.php file for auto-loading html, url, file, form and database.

This one time activity gives flexibility to uniformly use anywhere throughout the application without loading repeatedly.

$autoload['helper'] = array('html', 'url', 'file', 'form');
$autoload['libraries'] = array('database');

Database Configuration

Modify also application/config/database.php in order to establish the connection with database for performing database queries.

'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'roytuts',
'dbdriver' => 'mysqli',

Creating Controller Class

Create a controller file TagController.php under application/controllers with the following source code.

The below controller class handles request and response for clients.

This class basically validates input and send the input data to the model layer where actual database operation takes place in order to save the data into database.

Finally it sends success or failure message depending on success or failure operation.

The index() function first retrieves the tags from database and formats those tags, if available, for displaying into the input text area, so that user will understand what tags are there already into the database. Finally this function loads the view with existing tags. If no tag found then it simply displays the blank text area on view file.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of TagController
 *
 * @author https://roytuts.com
 */
class TagController extends CI_Controller {

    private $error;
    private $success;

    function __construct() {
        parent::__construct();
        $this->load->model('tagmodel', 'tag');
        $this->load->library('form_validation');
    }

    private function handle_error($msg) {
        $this->error .= '<p>' . $msg . '</p>';
    }

    private function handle_success($msg) {
        $this->success .= '<p>' . $msg . '</p>';
    }

    function index() {
        if ($this->input->post('add_tags')) {
            $this->form_validation->set_rules('tags', 'Tags', 'trim|required');

            $tags = $this->input->post('tags', TRUE);

            $related_tags = '';
            if (is_array(str_split($tags)) && count(str_split($tags)) > 2) {
                $tags = $this->format_tags_keywords($tags);
                $related_tags = explode(',', $tags);
            } else {
                $this->handle_error('Enter Tags');
            }


            if ($this->form_validation->run($this)) {
                $resp = $this->tag->add_tags($related_tags);
                if ($resp === TRUE) {
                    $this->handle_success('Tags are added successfully');
                }
            }

            $data['tags'] = $related_tags;
        }

        $data['errors'] = $this->error;
        $data['success'] = $this->success;
        $this->load->view('tag', $data);
    }


    private function format_tags_keywords($string) {
        preg_match_all('`(?:[^,"]|"((?<=\\\\)"|[^"])*")*`x', $string, $result);

        $tags = '';

		if (is_array($result) || is_object($result)) {
			foreach ($result as $arr) {
				$i = 0;
				foreach ($arr as $val) {
					if ($i % 2 == 1) {
						$i++;
						continue;
					}
					$tags .= $val . ',';
					$i++;
				}

				$tags = str_replace('[', '', $tags);
				$tags = str_replace(']', '', $tags);
				$tags = rtrim($tags, ',');
				$tags = str_replace('"', '', $tags);
				
				break;
			}
		}

        return $tags;
    }

}

Creating Model Class

We need a model class that will interact with database for performing database operations, such as, saving, retrieving, deleting, updating.

Here we will save our input tags into database using the model class.

Create a file TagModel.php under application/models folder with below source code.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of tagmodel
 *
 * @author https://roytuts.com
 */
class TagModel extends CI_Model {

    private $tag = 'tag';

    function __construct() {
        
    }

    function add_tags($tags) {
        if (!empty($tags)) {
            foreach ($tags as $tag) {
                $tag_array = array('tag_name' => $tag);
                $this->db->insert($this->tag, $tag_array);
            }
            return TRUE;
        }
        return NULL;
    }

}

Creating View File

We need a view file, where user will input tags or see existing tags.

We have added several jQuery libraries to implement our application.

We have added HTML form with text area, where user will input tags. This text area also displays the existing tags, if available, from the database.

If any error occurs or if user does not input any tag then error message appears above the form.

Create below view file tag.php under application/views with below source code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Create WordPress like add tags using Codeigniter</title>
        <link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/tags/textext.core.css"/>
        <link type="text/css" rel="stylesheet" href="<?php echo base_url(); ?>assets/css/tags/textext.plugin.tags.css"/>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/tags/textext.core.js"></script>
        <script type= 'text/javascript' src="<?php echo base_url(); ?>assets/js/tags/textext.plugin.tags.js"></script>
    </head>
    <body>
        <?php
        if (isset($success) && strlen($success)) {
            echo '<div style="color:green;">';
            echo $success;
            echo '</div>';
        }
        if (isset($errors) && strlen($errors)) {
            echo '<div style="color:red;">';
            echo $errors;
            echo '</div>';
        }
        if (validation_errors()) {
            echo '<div style="color:red;">';
            echo validation_errors();
            echo '</div>';
        }
        echo form_open($this->uri->uri_string(), array('id' => 'add_tags_form'));
        ?>
        <p>
            <label>Tags (type and press 'Enter')</label><br/>
            <textarea name="tags" id="tags" rows="5" cols="50" class="textarea"></textarea>
        </p>
        <p>
            <input type="submit" name="add_tags" id="add_tags" value="Save tags"/>
        </p>
        <?php
        echo form_close();
        ?>

        <script type="text/javascript">
            $('#tags').textext({
                        plugins: 'tags',
                        tagsItems: [<?php
							if (isset($tags) && (is_array($tags) || is_object($tags))) {
								$i = 1;
								foreach ($tags as $tag) {
									echo "'" . $tag . "'";
									if (count($tags) == $i) {
										echo '';
									} else {
										echo ',';
									}
									$i++;
								}
							}
						?>]
                    }).bind('tagClick', function (e, tag, value, callback) {
                        var newValue = window.prompt('Enter New value', value);
                        if (newValue)
                            callback(newValue);
                    });
        </script>
    </body>
</html>

Creating MySQL Table

Now in order to save our tags into table, we need to create a MySQL table.

CREATE TABLE IF NOT EXISTS tag (
    tag_id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    tag_name VARCHAR(50) NOT NULL
);

Configuring Route

We need to tell the application what is our default controller class that will be loaded by default on index URL hit.

$route['default_controller'] = 'tagcontroller';

Testing the Application

Home Page

Now hit the URL http://[::1]/codeIgniter-3.1.10-wordpress-tags/index.php in the browser to run the application. You will get similar page on the browser as shown in the below image.

wordpress like add tags using codeigniter and jquery

Error Page

When you try to save tags without input, then you will get below error.

wordpress like add tags using codeigniter and jquery

Success Page

Now add few tags and click on Save tags button, your tags will be saved into database and tags will be shown in the text area.

wordpress like add tags using codeigniter and jquery

Source Code

download source code

That’s all. Hope you got an idea on how to create WordPress like add tags using Codeigniter and jQuery.

Thanks for reading.

2 thoughts on “Create WordPress like add tags using Codeigniter and jQuery

  1. Hi,
    And thanks for this excellent tutorial.
    But I’ve got an error with preg_match_all :
    Message: preg_match_all(): Compilation failed: missing ) at offset 28
    Can you help me ? Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *